Search code examples
javaparsinghttpbyteresponse

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.


Solution

  • 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]