1
我可以当我使用下面的代码获取数据:根据我的文档Java,如何从HTTP POST方法获取连接响应代码?
private static String getHttpPostContent(String address, String token) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("token", token));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String serverResponse = EntityUtils.toString(entity);
return serverResponse;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
如果发生错误,然后服务器会发送错误418,告诉我发生了什么错误。我不知道如何去捕捉它?
当我使用HTTP GET方法,有一种方法如何检查响应代码,就像这样:
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK)
...
有在HTTP POST方法类似的方式?
您是否尝试观察httpResponse.getStatusLine()。getStatusCode()? – devnull
谢谢,完全正确。请把它写成答案。谢谢。 – Hesam