1

In my program I need to send a HTTP request and read the HTTP response body and headers.

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.

buræquete
  • 14,226
  • 4
  • 44
  • 89
e11438
  • 864
  • 3
  • 19
  • 33

1 Answers1

1

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);
buræquete
  • 14,226
  • 4
  • 44
  • 89
e11438
  • 864
  • 3
  • 19
  • 33
  • The code is not correct. You should not use `getInputStream()` and `getHeaderFields()` together becase you will get incomplete data. The reason for that is `getHeaderFields` internally calls `getInputStream` ( http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/net/www/protocol/http/HttpURLConnection.java#2092 ). For more details see comments here: https://stackoverflow.com/a/20976385/4682359 – Chris Ociepa Dec 29 '17 at 12:10