在 Android 中获取 400 HTTP 响应的响应正文?

发布于 2024-12-09 09:27:23 字数 899 浏览 0 评论 0原文

我正在与一个无法更改的 API 进行通信,当 API 端未验证请求时,该 API 会发送 400 响应。这是一个有效的 HTTP 请求,但请求数据未通过应用程序的验证规则。

400 响应包含一个 JSON 负载,其中包含有关请求未通过验证的原因的信息。

我似乎无法获取响应正文,因为抛出了 HttpRequestException。有人知道如何检索这个响应正文吗?

try {
        HttpUriRequest request = params[0];
        HttpResponse serverResponse = mClient.execute(request);

        BasicResponseHandler handler = new BasicResponseHandler();
        String response = handler.handleResponse(serverResponse);
        return response;
    } catch(HttpResponseException e) {
        // Threw HttpError
        Log.d(TAG, "HttpResponseException : " + e.getMessage());
        Log.d(TAG, "Status Code : " + e.getStatusCode());
        // TODO API returns 400 on successful HTTP payload, but invalid user data
        if(e.getStatusCode() == 400) {
                // Information on API error inside Response body
            }
   }

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 does not pass the application's validation rules.

The 400 response contains a JSON payload that has information on why the request did not pass validation.

I can't seem to get the response body because an HttpRequestException is thrown. Does anybody know how to retrieve this response body?

try {
        HttpUriRequest request = params[0];
        HttpResponse serverResponse = mClient.execute(request);

        BasicResponseHandler handler = new BasicResponseHandler();
        String response = handler.handleResponse(serverResponse);
        return response;
    } catch(HttpResponseException e) {
        // Threw HttpError
        Log.d(TAG, "HttpResponseException : " + e.getMessage());
        Log.d(TAG, "Status Code : " + e.getStatusCode());
        // TODO API returns 400 on successful HTTP payload, but invalid user data
        if(e.getStatusCode() == 400) {
                // Information on API error inside Response body
            }
   }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我恋#小黄人 2024-12-16 09:27:23

像这样,使用 org.apache.http.util.EntityUtils

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

PS:这是盲目编码,因为我不知道你尝试过什么。

获取状态码:

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

获取字节数组中的实体主体:

byte[] data = EntityUtils.toByteArray(response.getEntity());

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());
耶耶耶 2024-12-16 09:27:23

尝试这样:

if (this.responseCode == HttpURLConnection.HTTP_OK) {
 inputStream = httpUrlConnection.getInputStream();
} else {
inputStream = httpUrlConnection.getErrorStream();
}

Try that way:

if (this.responseCode == HttpURLConnection.HTTP_OK) {
 inputStream = httpUrlConnection.getInputStream();
} else {
inputStream = httpUrlConnection.getErrorStream();
}
夏九 2024-12-16 09:27:23

这就是我以 byte[] 形式发送和获取 Http 响应的方式。当然,如果需要,您可以将其更改为字符串。

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

希望有帮助!

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!

冷血 2024-12-16 09:27:23
                     if (serverResponseCode == 200) {

                     InputStream in = new BufferedInputStream(conn.getInputStream());
                     BufferedReader r = new BufferedReader(new InputStreamReader(in));
                     StringBuilder total = new StringBuilder();
                     for (String line; (line = r.readLine()) != null; ) {
                         total.append(line).append('\n');
                     }
                     Log.e("temp", String.valueOf(total));

                 }
                 else {
                     InputStream in = new BufferedInputStream(conn.getErrorStream());
                     BufferedReader r = new BufferedReader(new InputStreamReader(in));
                     StringBuilder total = new StringBuilder();
                     for (String line; (line = r.readLine()) != null; ) {
                         total.append(line).append('\n');
                     }
                     Log.e("temp", String.valueOf(total));

                 }
                     if (serverResponseCode == 200) {

                     InputStream in = new BufferedInputStream(conn.getInputStream());
                     BufferedReader r = new BufferedReader(new InputStreamReader(in));
                     StringBuilder total = new StringBuilder();
                     for (String line; (line = r.readLine()) != null; ) {
                         total.append(line).append('\n');
                     }
                     Log.e("temp", String.valueOf(total));

                 }
                 else {
                     InputStream in = new BufferedInputStream(conn.getErrorStream());
                     BufferedReader r = new BufferedReader(new InputStreamReader(in));
                     StringBuilder total = new StringBuilder();
                     for (String line; (line = r.readLine()) != null; ) {
                         total.append(line).append('\n');
                     }
                     Log.e("temp", String.valueOf(total));

                 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文