Java HTTP Response readResponse(URLConnection conn)

Here you can find the source of readResponse(URLConnection conn)

Description

read Response

License

Open Source License

Declaration

public static String readResponse(URLConnection conn) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;
import java.net.*;

public class Main {
    public static boolean printHeaders = false;

    public static String readResponse(URLConnection conn) throws Exception {
        BufferedReader in;//from  w  w  w.j a v a  2s  . c  o  m
        StringBuffer response = new StringBuffer();
        String line;

        try {
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        } catch (Exception ex) {
            InputStream err = ((HttpURLConnection) conn).getErrorStream();
            if (err == null) {
                System.err.println("Headers: " + getResponseHeaders(conn));
                throw ex;
            }
            in = new BufferedReader(new InputStreamReader(err));
        }

        if (printHeaders)
            response.append(getResponseHeaders(conn));

        while ((line = in.readLine()) != null)
            response.append(line + "\n");

        in.close();

        return response.toString();
    }

    public static String getResponseHeaders(URLConnection conn) {
        StringBuffer headers = new StringBuffer();
        String key;
        int n = 1;

        headers.append("\n----------\n");
        while ((key = conn.getHeaderFieldKey(n)) != null) {
            String value = conn.getHeaderField(n);
            headers.append(key + ": " + value + "\n");
            n++;
        }

        headers.append("----------\n");
        return headers.toString();
    }
}

Related

  1. getResponseText(URL constructedUrl, String encoding)
  2. getResposeText(HttpURLConnection connection)
  3. readResponse(HttpURLConnection conn, String encoding)
  4. readResponse(HttpURLConnection connection)
  5. readResponse(HttpURLConnection httpURLConnection)