0

i have a standard HttpServlet in my java web project. I use Netbeans. I want to call a Restfull Web service inside servlet and after i will catch the response like a JSON and populate a JSP. I tried to find on the net but i didn't find anything.

Thank you

2
  • 1
    I don't really understand the question, what exactly are you looking for? do you want a code example of how to call a restfull web service? or do you want to call your own created rest service? Commented Nov 13, 2015 at 8:46
  • An example! what didn't you understand? Commented Nov 13, 2015 at 8:47

1 Answer 1

1

Here's an example of HttpPost:

 try { HttpPost httpPost = new HttpPost("https://exampleurl/providerexample/api/v1/loansforexample" ); StringEntity params; params = new StringEntity("{" + "\"clientId\": \"" + "2" + "\"," + "\"productId\": \"" + "1" + "\"," + "\"locale\": \"" + "en" + "\"}"); httpPost.addHeader("Content-Type", "text/html"); //or text/plain httpPost.addHeader("Accept-Encoding", "gzip, deflate, sdch"); httpPost.setEntity(params); HttpResponse response = client.execute(httpPost); int statuscode = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity()); if (statuscode == 200) { System.out.println(responseBody); } if (statuscode != 200) { System.out.println(responseBody); // JSONObject obj = new JSONObject(responseBody); // JSONArray errors = obj.getJSONArray("errors"); // String errorMessage = ""; // if (errors.length() > 0) { // errorMessage = errors.getJSONObject(0).getString("developerMessage"); } } catch (Exception ex) { ex.printStackTrace(); ex.getMessage(); } 

HttpGet is pretty much the same.

Sign up to request clarification or add additional context in comments.

5 Comments

OK thank you. But My Request(GET/POST) has parameter text and response is a JSON
@LorenzoSogliani If this is your own RESTful webservice you can change what the rest service produces in the RESTFULsomethingFacade, if it's the other way around, you can change it in this line of code at the: httpPost.addHeader("Content-Type", "application/json"); to: httpPost.addHeader("Content-Type", "whatever you want");
@LorenzoSogliani I edited the code, as you can see I'm now posting text/html, and text/plain is another example of a format you can use.
Ok Thanks. tonight i'm testing it.
@LorenzoSogliani Glad to help :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.