简体   繁体   中英

parse http response bytes in java

I'm trying to parse a byte[] in java, which is a representation of an HTTP response. There is this question Is there any simple http response parser for Java? , which is exactly my question, but the accepted answer doesn't help me. If I look at http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/io/HttpMessageParser.html , I do not understand how this will help me.

I hope this should get you started

String s = "HTTP/1.1 200 OK\r\n" +
        "Content-Length: 100\r\n" +
        "Content-Type: text/plain\r\n" +
        "Server: some-server\r\n" +
        "\r\n";
SessionInputBufferImpl sessionInputBuffer = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), 2048);
sessionInputBuffer.bind(new ByteArrayInputStream(s.getBytes(Consts.ASCII)));
DefaultHttpResponseParser responseParser = new DefaultHttpResponseParser(sessionInputBuffer);
HttpResponse response = responseParser.parse();
System.out.println(response);

This code produces the following output:

HTTP/1.1 200 OK [Content-Length: 100, Content-Type: text/plain, Server: some-server]

Check this out: https://github.com/ipinyol/proxy-base

This is a simple highly configurable http proxy. The method readHeader of the class org.mars.proxybase.ProxyThread parses the http headers given a DataInputStream (which reads by bytes) and returns an object of type Header with information regarding the header.

Also, you probably know that either you have a content-length define in the header or you have chunked data that you must read by chunks in the http response. The methods readContent and readContentByChunk of the same class perform the reading of the content. You can explore your self the code and modify accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM