如何为Android HttpURLConnection实现getResponseMessage()/getResponseCode
我正在向HTTP服务器发出get和post请求。一切似乎都很好,但我需要从响应消息中获取状态代码。 这是我的发帖要求如何为Android HttpURLConnection实现getResponseMessage()/getResponseCode,android,httpurlconnection,Android,Httpurlconnection,我正在向HTTP服务器发出get和post请求。一切似乎都很好,但我需要从响应消息中获取状态代码。 这是我的发帖要求 postToHttp(URL url) throws IOException { StringBuilder stringBuilder = new StringBuilder(); DataOutputStream dataOutputStream = null; Log.i(TAG , "calling :: " + url.toString())
postToHttp(URL url) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
DataOutputStream dataOutputStream = null;
Log.i(TAG , "calling :: " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("city", "NYC");
jsonObject.put("country", "USA");
Log.i(TAG, "JSON onj :: " + jsonObject.toString());
dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}finally {
dataOutputStream.flush();
dataOutputStream.close();
}
//Need to check the post status?
}
只需调用urlConnection.getResponseCode()