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

时间:2019-01-17 18:36:59

标签: android httpurlconnection

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

 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?


}

1 个答案:

答案 0 :(得分:1)

只需调用urlConnection.getResponseCode()