Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Monday, February 6, 2017

How can I get an http response body as a string in Java?

How can I get an http response body as a string in Java?


I know there used to be a way to get it with apache commons as documented here: http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html and an example here:

http://www.kodejava.org/examples/416.html

but i believe this is deprecated. Is there any other way to make an http get request in java and get the response body as a string and not a stream?

Answer by WhiteFang34 for How can I get an http response body as a string in Java?


Every library I can think of returns a stream. You could use IOUtils.toString() from Apache Commons IO to read an InputStream into a String in one method call. E.g.:

URL url = new URL("http://www.example.com/");  URLConnection con = url.openConnection();  InputStream in = con.getInputStream();  String encoding = con.getContentEncoding();  encoding = encoding == null ? "UTF-8" : encoding;  String body = IOUtils.toString(in, encoding);  System.out.println(body);  

Update: I changed the example above to use the content encoding from the response if available. Otherwise it'll default to UTF-8 as a best guess, instead of using the local system default.

Answer by McDowell for How can I get an http response body as a string in Java?


This is relatively simple in the specific case, but quite tricky in the general case.

HttpClient httpclient = new DefaultHttpClient();  HttpGet httpget = new HttpGet("http://stackoverflow.com/");  HttpResponse response = httpclient.execute(httpget);  HttpEntity entity = response.getEntity();  System.out.println(EntityUtils.getContentMimeType(entity));  System.out.println(EntityUtils.getContentCharSet(entity));  

The answer depends on the Content-Type HTTP response header.

This header contains information about the payload and might define the encoding of textual data. Even if you assume text types, you may need to inspect the content itself in order to determine the correct character encoding. E.g. see the HTML 4 spec for details on how to do that for that particular format.

Once the encoding is known, an InputStreamReader can be used to decode the data.

This answer depends on the server doing the right thing - if you want to handle cases where the response headers don't match the document, or the document declarations don't match the encoding used, that's another kettle of fish.

Answer by moonlightcheese for How can I get an http response body as a string in Java?


Here's an example from another simple project I was working on using the httpclient library from Apache:

String response = new String();  List nameValuePairs = new ArrayList(1);  nameValuePairs.add(new BasicNameValuePair("j", request));  HttpEntity requestEntity = new UrlEncodedFormEntity(nameValuePairs);    HttpPost httpPost = new HttpPost(mURI);  httpPost.setEntity(requestEntity);  HttpResponse httpResponse = mHttpClient.execute(httpPost);  HttpEntity responseEntity = httpResponse.getEntity();  if(responseEntity!=null) {      response = EntityUtils.toString(responseEntity);  }  

just use EntityUtils to grab the response body as a String. very simple.

Answer by Eric Schlenz for How can I get an http response body as a string in Java?


How about just this?

org.apache.commons.io.IOUtils.toString(new URL("http://www.someurl.com/"));  

Answer by shahtapa for How can I get an http response body as a string in Java?


Here are two examples from my working project.

  1. Using EntityUtils and HttpEntity

    HttpResponse response = httpClient.execute(new HttpGet(URL));  HttpEntity entity = response.getEntity();  String responseString = EntityUtils.toString(entity, "UTF-8");  System.out.println(responseString);  
  2. Using BasicResponseHandler

    HttpResponse response = httpClient.execute(new HttpGet(URL));  String responseString = new BasicResponseHandler().handleResponse(response);  System.out.println(responseString);  

Answer by Akshay for How can I get an http response body as a string in Java?


The Answer by McDowell is correct one. However if you try other suggestion in few of the posts above.

HttpEntity responseEntity = httpResponse.getEntity();  if(responseEntity!=null) {     response = EntityUtils.toString(responseEntity);     S.O.P (response);  }  

Then it will give you illegalStateException stating that content is already consumed.

Answer by lkamal for How can I get an http response body as a string in Java?


Below is a simple way of accessing the response as a String using Apache HTTP Client library.

import org.apache.http.HttpResponse;  import org.apache.http.client.HttpClient;  import org.apache.http.client.ResponseHandler;  import org.apache.http.client.methods.HttpGet;  import org.apache.http.impl.client.BasicResponseHandler;    //...     HttpGet get;  HttpClient httpClient;    // initialize variables above    ResponseHandler responseHandler = new BasicResponseHandler();  String responseBody = httpClient.execute(get, responseHandler);  

Answer by Subhasish Sahu for How can I get an http response body as a string in Java?


We can use the below code also to get the HTML Response in java

import org.apache.http.client.HttpClient;  import org.apache.http.client.methods.HttpGet;  import org.apache.http.impl.client.DefaultHttpClient;  import org.apache.http.HttpResponse;  import java.io.BufferedReader;  import java.io.InputStreamReader;  import org.apache.log4j.Logger;    public static void main(String[] args) throws Exception {      HttpClient client = new DefaultHttpClient();      //  args[0] :-  http://hostname:8080/abc/xyz/CheckResponse      HttpGet request1 = new HttpGet(args[0]);      HttpResponse response1 = client.execute(request1);      int code = response1.getStatusLine().getStatusCode();        try (BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));) {          // Read in all of the post results into a String.          String output = "";          Boolean keepGoing = true;          while (keepGoing) {              String currentLine = br.readLine();                if (currentLine == null) {                  keepGoing = false;              } else {                  output += currentLine;              }          }            System.out.println("Response-->" + output);      } catch (Exception e) {          System.out.println("Exception" + e);        }  }  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.