Andrzej Andrzej - 9 months ago 68
Java Question

How to read full response from HttpURLConnection?

I make some proxy server in andorid which modify http headers, it works ok, but I have to forward full response to 'top layer'.

How I can read whole response (all headers, content, everything) from HttpURLConnection?

HttpURLConnection httpURLConnection;
URL url = new URL(ADDRESS);
httpURLConnection = (HttpURLConnection) url.openConnection();
// add headers, write output stream, flush
if (httpURLConnection.getResponseCode() == HttpsURLConnection.HTTP_OK)
Map<String, List<String>> map = httpURLConnection.getHeaderFields();
System.out.println("Printing Response Header...\n");

for (Map.Entry<String, List<String>> entry : map.entrySet())
System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue());

return new DataInputStream(httpURLConnection.getInputStream());

In getInputStream I received only content it is possible to have some stream with whole reposne?

Answer Source

There's no way to dump the full HTTP response directly using the HttpURLConnection, but you can use its various method to reconstruct it. For example,

HttpURLConnection httpURLConnection;
URL url = new URL("");
httpURLConnection = (HttpURLConnection) url.openConnection();
StringBuilder builder = new StringBuilder();
       .append(" ")

Map<String, List<String>> map = httpURLConnection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet())
    if (entry.getKey() == null) 
    builder.append( entry.getKey())
           .append(": ");

    List<String> headerValues = entry.getValue();
    Iterator<String> it = headerValues.iterator();
    if (it.hasNext()) {

        while (it.hasNext()) {
            builder.append(", ")




200 OK
X-Frame-Options: SAMEORIGIN
Transfer-Encoding: chunked
Date: Tue, 07 Jan 2014 16:06:45 GMT
P3P: CP="This is not a P3P policy! See for more info."
X-XSS-Protection: 1; mode=block
Expires: -1
Alternate-Protocol: 80:quic
Set-Cookie: NID=67=OIu8_xhcxE-UPCSfIoTINvRyOe4ALVhIqan2NUI6LMdRkSJHTPGvNkYeYE--WqPSEPK4c4ubvmjWGUyFgXsa453KHavX9gUeKdzfInU2Q25yWP3YtMhsIhJpUQbYL4gq; expires=Wed, 09-Jul-2014 16:06:45 GMT; path=/;; HttpOnly, PREF=ID=4496ed99b812997d:FF=0:TM=1389110805:LM=1389110805:S=jxodjb3UjGJSZGaF; expires=Thu, 07-Jan-2016 16:06:45 GMT; path=/;
Content-Type: text/html; charset=ISO-8859-1
Server: gws
Cache-Control: private, max-age=0

You can then get the InputStream and print its content too.