Android 如何访问 HttpURLConnection InputStream 返回的 HttpResponse?

How to access HttpResponse returned by HttpURLConnection InputStream in Android?

我已采用 中的代码成功地 POST JSON 从我的 Android 应用程序到 Python/Django 服务器。这是我(非常接近)改编的 POST 代码:

// In my activity's onCreate method
try {
    JSONObject obj = new JSONObject(strJSON);
    new postJSON().execute("https://www.placeholder.com/generate_json", obj.toString());
} catch (Throwable t) {
    Log.e("JSON Error", "Could not parse malformed JSON: " + strJSON);
}

// Outside onCreate
private class postJSON extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        String data = "";
        HttpURLConnection httpURLConnection = null;

        try {
            httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes("PostData=" + params[1]);
            wr.flush();
            wr.close();

            InputStream in = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(in);

            int inputStreamData = inputStreamReader.read();
            while (inputStreamData != -1) {
                char current = (char) inputStreamData;
                inputStreamData = inputStreamReader.read();
                data += current;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.e("TAG", result);
    }
}

我现在想访问服务器返回的HttpResponse,我认为它包含在data中(但我对此不确定)。如果 data 确实包含 HttpResponse,我想在 Toast 中打印它。

data 是否已经包含来自服务器的 HttpResponse,或者我是否需要采取额外的步骤从 InputStream 获取它?如果它已经存在,我应该将我的 Toast.makeText 代码放在哪里以在 Toast 中打印 HttpResponse(即 data)?

变量 data 是一个包含来自服务器的响应主体的 String,您可以在您的 UI 线程上作为变量 result 在方法 onPostExecute

从异步任务中获取结果有多种模式。这是一个简单的方法,试试这个方法干杯吧。

这样写你的任务执行:

// In your activity's onCreate method
try {
    JSONObject obj = new JSONObject(strJSON);
    new postJSON() {

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
        }

    }.execute("https://www.placeholder.com/generate_json", obj.toString());
} catch (Throwable t) {
    Log.e("JSON Error", "Could not parse malformed JSON: " + strJSON);
}