我有这样的代码:
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 Forbidden 来获取错误消息,我也希望得到响应
The BasicResponseHandler
仅当返回成功代码 (2xx) 时才返回您的数据。但是,您可以非常轻松地编写自己的ResponseHandler
始终将响应正文返回为String
, e.g.
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
return EntityUtils.toString(response.getEntity());
}
};
或者,您可以使用其他重载执行方法 http://developer.android.com/reference/org/apache/http/client/HttpClient.html#execute%28org.apache.http.client.methods.HttpUriRequest%29 on HttpClient
这不需要ResponseHandler
并返回给您HttpResponse
直接地。然后打电话EntityUtils.toString(response.getEntity())
以同样的方式。
要获取响应的状态代码,您可以使用HttpResponse.getStatusLine().getStatusCode()
并与其中的静态整数之一进行比较HttpStatus
班级。例如。代码“403”是HttpStatus.SC_FORBIDDEN
。您可以根据返回的状态代码采取与您的应用程序相关的特定操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)