0

I have adopted the code in this Stack Overflow answer to successfully POST JSON from my Android app to a Python/Django server. Here is my (very close) adaptation of the POST code:

// 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). If data does contain the HttpResponse, I would like to print it in a Toast.

Does data already contain the HttpResponse from the server or do I need to take additional steps to get it from InputStream? If it is already there, where should I put my Toast.makeText code to print the HttpResponse (i.e. data) in a Toast?

  • Yes `String data` contains the response. And it is returned by doInBackground. So it is available as parameter in onPostExecute. Toast it there. You already log it there. So in the logs you could see if it is indeed the expected json. As you already logged it i do not understand your problem anymore. – greenapps Dec 14 '17 at 20:57
  • Thanks for the advice! I should use `result` in `onPostExecute` to view and manipulate the response, correct? – ThanksForTheHelpAgain Dec 14 '17 at 21:11
  • Indeed. Thats how it should be done. – greenapps Dec 14 '17 at 21:18

1 Answers1

0

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

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);
}
Dave Thomas
  • 3,667
  • 2
  • 33
  • 41
  • `There are many patterns for adding a callback to the async task to handle the result once it completes. Here is one simple way to do it,` ?? You did not add or use a callback. – greenapps Dec 14 '17 at 21:01
  • 1
    Thanks for posting this! I didn't realize that I could use onPostExecute in the onCreate method. I just ran this code and it launched with no errors, but the log showed me that there's a connection issue on my server. I think you're code works but I'll confirm it once I fix my server asap. – ThanksForTheHelpAgain Dec 14 '17 at 21:18