简体   繁体   English

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

[英]How to access HttpResponse returned by HttpURLConnection InputStream in Android?

I have adopted the code in this Stack Overflow answer to successfully POST JSON from my Android app to a Python/Django server. 我已采用此Stack Overflow答案中的代码成功将JSON从我的Android应用程序发布到Python / Django服务器。 Here is my (very close) adaptation of the POST code: 这是我(非常接近)对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);
    }
}

I now want to access the HttpResponse returned by the server, which I think is contained in data (but I'm not sure about this). 现在,我想访问服务器返回的HttpResponse,我认为它包含在data (但我不确定)。 If data does contain the HttpResponse, I would like to print it in a Toast. 如果data确实包含HttpResponse,我想在Toast中打印它。

Does data already contain the HttpResponse from the server or do I need to take additional steps to get it from InputStream ? data是否已经包含来自服务器的HttpResponse,或者我是否需要采取其他步骤从InputStream获取它? If it is already there, where should I put my Toast.makeText code to print the HttpResponse (ie data ) in a Toast? 如果已经存在,应该在哪里放置Toast.makeText代码以在Toast中打印HttpResponse(即data )?

The variable data is a String containing the response body from the server and will be available to you on your UI thread as the variable result in the method onPostExecute 变量data是一个String其中包含来自服务器的响应正文,并将在方法onPostExecute作为变量result在UI线程onPostExecute

There are many patterns for getting the result from an async task. 从异步任务获取结果的方式有很多种。 Here is one simple way to do it, try this approach to get a toast. 这是一种简单的方法,尝试这种方法烤面包。

Write your execution of the task as such: 这样编写任务的执行:

// 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android没有读取完整的HttpURLConnection InputStream内容 - Android is not reading full HttpURLConnection InputStream content 为什么android HttpURLConnection缓存输入流结果? - Why android HttpURLConnection cache the inputstream results? 如何在 HttpResponse.BodyHandler 中使用 InputStream? - How to consume an InputStream in an HttpResponse.BodyHandler? 从HttpURLConnection中的getErrorStream返回的InputStream中获取从服务器发送的有用数据 - Get the useful data sent from server in InputStream returned by getErrorStream in HttpURLConnection HttpURLConnection如何获取其inputStream实例? - How HttpURLConnection get's its inputStream instance? Android:如何从InputStream进行随机访问? - Android: how to have random access from an InputStream? 如何在Android中阅读HttpResponse? - How to read HttpResponse in Android? Android HttpUrlConnection InputStream读取错误(JSONException:未终止的数组) - Android HttpUrlConnection InputStream reading error(JSONException: Unterminated array) 从android中的HttpURLConnection获取InputStream时获取UnknownLengthHttpInputStream - Getting UnknownLengthHttpInputStream while getting InputStream from HttpURLConnection in android 带有https InputStream的HttpURLConnection出现乱码 - HttpURLConnection with https InputStream Garbled
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM