e11438 e11438 - 2 months ago 13
HTTP Question

Read HTTP response header and body from one HTTP request in java

In my java program i need to send a HTTP request and read the HTTP response body and headers. When i'm googling about this i get separate answers on how to read response headers and response body.

So i added those examples together as follows.

URL obj = new URL("http://localhost:8080/SpringSecurity/admin");
URLConnection conn = obj.openConnection();

//get all headers
Map<String, List<String>> map = conn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() +
" ,Value : " + entry.getValue());
}
ByteArrayOutputStream output = (ByteArrayOutputStream) conn.getOutputStream();

byte[] input = output.toByteArray();
System.out.println(input.length);


It prints the headers but it doesn't print the length of byte array
input
.

Can someone explain why this is happening and example of reading both HTTP response headers and body.

Answer

What I've done wrong in this one is opening an output stream that writes to the connection using conn.getOutputStream(). So I opened an input stream that reads from the connection using conn.getInputStream().

So the corrected form of code is,

        URL obj = new URL("http://localhost:8080/SpringSecurity/admin");          
        URLConnection conn = obj.openConnection();

        //get all response headers
        Map<String, List<String>> map = conn.getHeaderFields();
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        System.out.println("Key : " + entry.getKey() +
                 " ,Value : " + entry.getValue());
        }
        //get response body
        InputStream output =  conn.getInputStream();
        Scanner s = new Scanner(output).useDelimiter("\\A");
        String result = s.hasNext() ? s.next() : "";
        System.out.println(result);