获取错误请求httpURLConnection.getInputStream()的正文 [英] get body of Bad Request httpURLConnection.getInputStream()

查看:488
本文介绍了获取错误请求httpURLConnection.getInputStream()的正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究使用Restful Web服务获取信息的Portlet. 因此,当我致电webservice且人员ID不存在时,它会返回适当的错误消息 JSON格式(错误请求代码-400),并且如果人员ID有效,则返回json中的人员信息(代码200).

I've work on a portlet that use Restful web service to get info. so, when i call webservice and person id was not exist, it return an appropriate error message in json format (with Bad request code - 400), and if person id be valid, return person info in json (with code 200).

现在,我如何读取响应正文(包含错误描述),因为 调用"httpConn.getInputStream()"会在错误的请求模式下引发异常.

now, how can i read body of response (that contain error description) because invoking "httpConn.getInputStream()" will throw exception in bad request mode.

这部分代码:

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. :)

推荐答案

使用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);

这篇关于获取错误请求httpURLConnection.getInputStream()的正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆