获取错误请求的主体httpURLConnection.getInputStream()

时间:2014-02-03 11:23:53

标签: httpurlconnection

我正在使用Restful Web服务获取信息的portlet。 因此,当我调用webservice并且人员ID不存在时,它会返回相应的错误消息 以json格式(带有Bad请求代码 - 400),如果person id有效,则返回json中的人员信息(代码为200)。

现在,我如何阅读响应体(包含错误描述),因为 调用“httpConn.getInputStream()”将在错误请求模式下抛出异常。

我的代码的这一部分:

HttpURLConnection httpConn = null;
URL url = new URL("http://192.168.1.20/personinfo.html?id=30");   
URLConnection connection = url.openConnection();
httpConn = (HttpURLConnection) connection;
httpConn.setRequestProperty("Accept", "application/json");
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("charset", "utf-8");
System.out.println("befor getInputStream *******");
BufferedReader br = null;
if (!(httpConn.getResponseCode() == 400)) {
     br = new BufferedReader(new InputStreamReader((httpConn.getInputStream())));
     String output;
     StringBuilder builder = new StringBuilder();
     System.out.println("Output from Server .... \n");
     while ((output = br.readLine()) != null) 
          builder.append(output);
     return builder.toString();
}else
   here must detect error message. :)

3 个答案:

答案 0 :(得分:35)

如果响应代码不成功,您必须使用HttpURLConnection.getErrorStream()读取正文。

答案 1 :(得分:7)

您可以使用以下代码在 HttpURLConnection 中获取错误请求的正文:

InputStream errorstream = connection.getErrorStream();

String response = "";

String line;

BufferedReader br = new BufferedReader(new InputStreamReader(errorstream));

while ((line = br.readLine()) != null) {
    response += line;
}

Log.d("body of Bad Request HttpURLConnection", "Response: " + response);

答案 2 :(得分:2)

使用Apache Httpclient:

        String url = "http://192.168.1.6:7003/life/lifews/getFirstInstallment.html?rootPolicyNo=1392/2126/2/106/9995/1904&token=1984";
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);

        // add request header
        HttpResponse response = client.execute(request);
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        System.out.println(result);