Here you can find the source of getResponse(HttpURLConnection httpConn, StringBuilder responseContent, StringBuilder responseCode, HashMap
Parameter | Description |
---|---|
httpConn | a parameter |
Parameter | Description |
---|---|
IOException | an exception |
public static void getResponse(HttpURLConnection httpConn, StringBuilder responseContent, StringBuilder responseCode, HashMap<String, String> headers) throws IOException
//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; import java.net.URLConnection; import java.util.HashMap; public class Main { /**//from ww w. ja v a2 s. c o m * Get the response content and headers as string * * @param httpConn * @return * @throws IOException */ public static void getResponse(HttpURLConnection httpConn, StringBuilder responseContent, StringBuilder responseCode, HashMap<String, String> headers) throws IOException { String s = getResponseContent(httpConn); responseContent.setLength(0); responseContent.append(s); s = getResponseHeaders(httpConn, headers); responseCode.setLength(0); responseCode.append(s); return; } /** * 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 headers * * @param conn * @param headers * @return 1st response line */ public static String getResponseHeaders(URLConnection conn, HashMap<String, String> headers) { headers.clear(); String responseCode = ""; for (int i = 0;; i++) { String name = conn.getHeaderFieldKey(i); String value = conn.getHeaderField(i); if (name == null && value == null) { break; } if (name == null) { responseCode = value; } else { headers.put(name, value); } } return responseCode; } /** * 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(); } } }