在HttpClient的403后,Android获得响应HttpClient、Android

2023-09-08 09:38:36 作者:一生孤妄づ

我有一个code是这样的:

I have a code like this:

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(server);

try {
    JSONObject params = new JSONObject();
    params.put("email", email);

    StringEntity entity = new StringEntity(params.toString(), "UTF-8");
    httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
    httpPost.setEntity(entity);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpClient.execute(httpPost, responseHandler);
    JSONObject response = new JSONObject(responseBody);
        fetchUserData(response);

    saveUserInfo();

    return true;
} catch (ClientProtocolException e) {
    Log.d("Client protocol exception", e.toString());
    return false;
} catch (IOException e) {
    Log.d`enter code here`("IOEXception", e.toString());
    return false;
} catch (JSONException e) {
    Log.d("JSON exception", e.toString());
    return false;
}

和我想有一个响应,即使我有HTTP 403禁止获得错误信息

And i want to have a response even if I have HTTP 403 Forbidden to get error message

推荐答案

该如果成功,code(2XX)返回 BasicResponseHandler 只返回数据。但是,你可以很轻松地编写自己的 ResponseHandler所总是返回响应为字符串,例如

The BasicResponseHandler only returns your data if a success code (2xx) was returned. However, you can very easily write your own ResponseHandler to always return the body of the response as a String, e.g.

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
    @Override
    public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
        return EntityUtils.toString(response.getEntity());
    }
    };

另外,你可以使用other超载对的HttpClient execute方法它不需要 ResponseHandler所,并返回了 Htt的presponse 直接。然后调用 EntityUtils.toString(response.getEntity())以同样的方式。

Alternatively, you can use the other overloaded execute method on HttpClient which does not require a ResponseHandler and returns you the HttpResponse directly. Then call EntityUtils.toString(response.getEntity()) in the same way.

要得到回应的状态code,可以使用的Htt presponse.getStatusLine()的getStatus code()和比较要在的HTTPStatus 类中的静态整数之一。例如。 code'403'是 HttpStatus.SC_FORBIDDEN 。你可以采取具体行动的应用程序相关的根据状态code返回。

To get the status code of a response, you can use HttpResponse.getStatusLine().getStatusCode() and compare to to one of the static ints in the HttpStatus class. E.g. code '403' is HttpStatus.SC_FORBIDDEN. You can take particular actions as relevant to your application depending on the status code returned.

 
精彩推荐
图片推荐