Search code examples
javadatabaseweb-servicesrequestresponse

How to get data from response


I have created 2 web services and I was able to send some data.

Using this three lines of code

HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz");
HttpResponse response = client.execute(request);

In this situation, the method that I posted send to a Web Server the 2 data.

@Path("/domethod")
    // Produces JSON as response
    @Produces(MediaType.APPLICATION_JSON) 
    // Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
    public String doLogin(@QueryParam("data1") String d1, @QueryParam("data2") String d2){
        String response = "";
        System.out.println("Data: d1="+d1+"; d2="+d2);
        if(checkData(d1, d1)){
            response = Utitlity.constructJSON("tag",true);
        }else{
            response = Utitlity.constructJSON("tag", false, "Error");
        }
    return response;        
    }

System.out works correctely and print: d1=abc; d2=xyz But now the application isn't able to return response to the first method. How I can get the response?


Solution

  • You're already getting the response here:

    HttpResponse response = client.execute(request);
    

    And since you're already using org.apache.httpcomponents you can do something like:

    String result = EntityUtils.toString(response.getEntity());
    

    After that you have your data as a string, simply do what you wish with it.

    EDIT: A little bit more information, your data is in the entity of the response, which is an HttpEntity object. You can get the content from there as an InputStream and read it as you wish, my example was for a simple string.