How do I get Http response body as a string?

This example show you how to get Http response body as a string when using the Apache HttpComponents library. To get the response body as a string we can use the EntityUtils.toString() method. This method read the content of an HttpEntity object content and return it as a string. The content will be converted using the character set from the entity object.

Let’s see the code snippet below:

package org.kodejava.example.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class EntityAsString {
    public static void main(String[] args) {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://www.kodejava.org");

        try {
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();

            //
            // Read the contents of an entity and return it as a String.
            //
            String content = EntityUtils.toString(entity);
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

1 Comments

  1. Iam a new bie for this , all the article is really gud.I have one doubt , what will be the status code after the post method.Since iam getting 200

Leave a Reply