Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any simple http response parser for Java?

Tags:

java

http

Is there any simple http response parser implementation? The idea is to put in the complete response as one big string and be able to retrieve stuff like statuscode, body etc. through the interface.

The requests/responses are not sent directly over TCP/IP so there is no need for anything but the core rfc 2616 parsing implementation.

like image 737
mibollma Avatar asked Feb 13 '12 13:02

mibollma


People also ask

How do you read a response body in Java?

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.

What is HTTP Response in Java?

An HTTP response. An HttpResponse is not created directly, but rather returned as a result of sending an HttpRequest . An HttpResponse is made available when the response status code and headers have been received, and typically after the response body has also been completely received.

What is HttpClient in Java?

An HTTP Client. An HttpClient can be used to send requests and retrieve their responses. An HttpClient is created through a builder . The builder can be used to configure per-client state, like: the preferred protocol version ( HTTP/1.1 or HTTP/2 ), whether to follow redirects, a proxy, an authenticator, etc.


1 Answers

If you use for instance Apache HttpClient you will get a java response object which you can use to extract headers or the message body. Consider the following sample

HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet("http://www.foo.com/"));
Header[] headers = response.getAllHeaders();
InputStream responseBody = response.getEntity().getContent();

If you only want to parse a reponse, perhaps the HttpMessageParser will be useful:

Abstract message parser intended to build HTTP messages from an arbitrary data source.

like image 164
Johan Sjöberg Avatar answered Sep 23 '22 05:09

Johan Sjöberg