Get response body on 400 HTTP response in Android?

后端 未结 3 1444
攒了一身酷
攒了一身酷 2021-01-28 16:00

I\'m communicating with an API that I can not change that sends a 400 response when a request is not validated on the API side. It is a valid HTTP request, but the request data

相关标签:
3条回答
  • 2021-01-28 16:08

    Try that way:

    if (this.responseCode == HttpURLConnection.HTTP_OK) {
     inputStream = httpUrlConnection.getInputStream();
    } else {
    inputStream = httpUrlConnection.getErrorStream();
    }
    
    0 讨论(0)
  • 2021-01-28 16:13

    Something like this, using org.apache.http.util.EntityUtils:

    HttpRequestBase base = new HttpGet(url);
    HttpResponse response = httpClient.execute(base);
    String jsonString = EntityUtils.toString(response.getEntity());
    

    PS: This is blind coding as I don't know what you tried yet.

    To get status code:

    int statusCode = response.getStatusLine().getStatusCode();
    

    To get the entity body in byte array:

    byte[] data = EntityUtils.toByteArray(response.getEntity());
    
    0 讨论(0)
  • 2021-01-28 16:28

    This is how I send and get Http response as an byte[].Of course you can change it to string if you want.

                    byte[] buffer = new byte[1024];
                    httpclient = new DefaultHttpClient();
                    httppost = new HttpPost("http://www.rpc.booom.com");
    
    
    
                    postParameters = new ArrayList<NameValuePair>();
                    postParameters.add(new BasicNameValuePair("debug_data","1"));
                    postParameters.add(new BasicNameValuePair("client_api_ver", "1.0.0.0"));
                    postParameters.add(new BasicNameValuePair("device_identificator", deviceId));
                    postParameters.add(new BasicNameValuePair("device_resolution", resolution));
                    postParameters.add(new BasicNameValuePair("username_hash", hashUser(username,password)));
                    postParameters.add(new BasicNameValuePair("password_hash", hashPass(username,password)));
    
                    httppost.setEntity(new UrlEncodedFormEntity(postParameters));
    
                    HttpResponse response = httpclient.execute(httppost);
                    Log.w("Response ","Status line : "+ response.getStatusLine().toString());
                    buffer = EntityUtils.toString(response.getEntity()).getBytes();
    

    Hope it helps!

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