Reputation: 904
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.
Upvotes: 1
Views: 7232
Reputation: 904
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);
Upvotes: 1