Java HTTP Response getResponseContent(HttpURLConnection httpConn)

Here you can find the source of getResponseContent(HttpURLConnection httpConn)

Description

Get the response (or error response) as a string

License

Apache License

Parameter

Parameter Description
httpConn a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static String getResponseContent(HttpURLConnection httpConn) throws IOException 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;

public class Main {
    /**/* w w w  .j ava  2 s.  co  m*/
     * Get the response (or error response) as a string
     * 
     * @param httpConn
     * @return
     * @throws IOException
     */
    public static String getResponseContent(HttpURLConnection httpConn) throws IOException {
        try {
            if (httpConn.getInputStream() == null) {
                return null;
            } else {
                StringBuilder sb = new StringBuilder();
                BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                String str;
                while ((str = in.readLine()) != null) {
                    sb.append(str + "\n");
                }
                in.close();

                return sb.toString();
            }
        } catch (Exception ex) {
            return getResponseErrorContent(httpConn);
        }
    }

    /**
     * Gets the error response as a string
     * 
     * @param httpConn
     * @return
     * @throws IOException
     */
    public static String getResponseErrorContent(HttpURLConnection httpConn) throws IOException {
        if (httpConn.getErrorStream() == null) {
            return null;
        } else {
            StringBuilder sb = new StringBuilder();
            BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
            String str;
            while ((str = in.readLine()) != null) {
                sb.append(str + "\n");
            }
            in.close();

            return sb.toString();
        }
    }
}

Related

  1. getResponse(URL request)
  2. getResponse(URL url)
  3. getResponseAsString(HttpURLConnection conn)
  4. getResponseBody(HttpURLConnection conn)
  5. getResponseContent(HttpURLConnection connection)
  6. getResponseContent(String url)
  7. getResponseErrorContent(HttpURLConnection httpConn)
  8. getResponseHeader(HttpURLConnection conn)
  9. getResponseHeader(String headerName, HttpURLConnection urlConnection)