2

I am getting responses in JSON format when I make API requests to an api.

I am getting this when I do the System.Out.Println of the response.

HTTP/1.1 200 OK [Date: Thu, 04 Oct 2012 20:33:18 GMT, Server: Apache/1.3.33 (Unix) PHP/4.4.0, Cache-control: no-cache, must-revalidate, no-cache="Set-Cookie", private, Expires: Fri, 01 Jan 1990 00:00:00 GMT, Pragma: no-cache, X-CreationTime: 0.051, Set-Cookie: DT=1349382798:29998:365-l4; path=/; expires=Fri, 01-Jan-2020 00:00:00 GMT; domain=.wunderground.com, Connection: close, Transfer-Encoding: chunked, Content-Type: application/json; charset=UTF-8]

But it is not the expected response, the response should be like this,

response: {
name:
class:
}

I am using Apache HTTP Client.

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url); 
HttpResponse response = httpclient.execute(httpget);
System.out.println(response);

What should I do next in order to get the expected result? I just need a point in right direction.

2 Answers 2

3

I am answering my own question here:

After a little bit of more research on Apache website, I found this:

HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));

Believe me it is lot more easier and works like a charm.

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

Comments

2

You'll need to do something like this instead:

HttpResponse response = httpclient.execute(httpget);
StringBuilder sb = new StringBuilder();
DataInputStream in = new DataInputStream(response.getEntity().getContent()); 
String line;     
while ((line = in.readLine()) != null) { 
    sb.append(line);
} 
in.close(); 
String json = sb.toString(); 

1 Comment

For reference, it would be much more efficient to use a CharBuffer with InputStream.read(CharBuffer) instead of the series of String objects returned by BufferedInputStream.getLine(). It saves on both memory allocation and searching for line breaks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.