Get body of Bad Request httpURLConnection.getInputStream()

后端 未结 3 512
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 20:55

I\'ve been working on a portlet that calls Rest API. When the API is called and the requested data doesn\'t exist, it returns an appropriate error message in JSON format (wi

相关标签:
3条回答
  • 2020-12-15 21:49

    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);
    
    0 讨论(0)
  • 2020-12-15 21:51

    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);
    
    0 讨论(0)
  • 2020-12-15 21:51

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

    0 讨论(0)
提交回复
热议问题