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.apache.http;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class EntityAsString {
public static void main(String[] args) {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpGet request = new HttpGet("https://kodejava.org");
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();
}
}
}
Maven Dependencies
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
I am a newbie for this, all the article is really good. I have one doubt, what will be the status code after the post method. Since I am getting 200.
Hi Priyan, the
200
status code is equal toHttpServletResponse.SC_OK
. The following URL give you the complete status code.@Wayan : Your code helped me, this is exactly what I was looking for. Thanks.
Thanks a lot! The article was very helpful!
How to convert HttpResponse to ResponseEntity