Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/187.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何为Android HttpURLConnection实现getResponseMessage()/getResponseCode_Android_Httpurlconnection - Fatal编程技术网

如何为Android HttpURLConnection实现getResponseMessage()/getResponseCode

如何为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())

我正在向HTTP服务器发出get和post请求。一切似乎都很好,但我需要从响应消息中获取状态代码。 这是我的发帖要求

 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()