gpt4 book ai didi

java - Android 在 HttpClient 中的 403 后得到响应

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:26:57 29 4
gpt4 key购买 nike

我有这样的代码:

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 禁止获取错误消息,我也想得到响应

最佳答案

BasicResponseHandler 仅在返回成功代码 (2xx) 时才返回您的数据。但是,您可以非常轻松地编写自己的 ResponseHandler 以始终将响应主体作为 String 返回,例如

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

或者,您可以使用 other overloaded execute methodHttpClient 上不需要 ResponseHandler 并直接返回 HttpResponse。然后以同样的方式调用EntityUtils.toString(response.getEntity())

要获取响应的状态代码,您可以使用 HttpResponse.getStatusLine().getStatusCode() 并与 HttpStatus 中的静态整数之一进行比较类(class)。例如。代码“403”是 HttpStatus.SC_FORBIDDEN。您可以根据返回的状态代码执行与您的应用程序相关的特定操作。

关于java - Android 在 HttpClient 中的 403 后得到响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7025213/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com