首页 > 解决方案 > 如何为 Android HttpURLConnection 实现 getResponseMessage() / getResponseCode

问题描述

我正在向 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?


}

标签: androidhttpurlconnection

解决方案


只需调用 urlConnection.getResponseCode()


推荐阅读