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