get body of Bad Request httpURLConnection.getInputStream()

我怕爱的太早我们不能终老 提交于 2019-11-29 16:56:51

问题


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

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

this part of my code:

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

回答1:


Use 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);



回答2:


In case of non-successful response codes, you have to read the body with HttpURLConnection.getErrorStream().




回答3:


you can get body of Bad Request in HttpURLConnection using this code :

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


来源:https://stackoverflow.com/questions/21526082/get-body-of-bad-request-httpurlconnection-getinputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!