0

I cant handle onpostexecute result because doInBackground seems to return an object that i should convert to string in order to show.

this is the screen with the response of OnPostExecute:

screen

the question is how obtain JSON RESPONSE

public class PostTask extends AsyncTask<URL, String, String> {

        String error = "";
        boolean flag = false;
        Context mContext = null;

        public PostTask(Context context) {
            mContext = context;
        }

        @Override
        protected String doInBackground(URL... data) {


            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("https://example.it");

            HttpResponse response = null;
            try {

                //add data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(      1);
                nameValuePairs.add(new BasicNameValuePair("username", "xxxxxxxxxx"));
                nameValuePairs.add(new BasicNameValuePair("password", "xxxxxxxxxx"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                //execute http post
                response = httpclient.execute(httppost);



            } catch (Exception e) {
                Toast.makeText(mContext, e.getMessage(),Toast.LENGTH_LONG).show();
                flag = true;
                error = e.getMessage();
                e.printStackTrace();
            }

            return response.toString();

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(flag){
                Toast.makeText(mContext, "HttpHostConnectException Occured: "+error, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(mContext, "DONE "+s, Toast.LENGTH_SHORT).show();
            }

        }

5 Answers5

1

THIS WORKED FOR ME:

public class PostTask extends AsyncTask<URL, String, String> {

    String error = "";
    boolean flag = false;
    Context mContext = null;

    public PostTask(Context context) {
        mContext = context;
    }

    @Override
    protected String doInBackground(URL... data) {


        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("https://example.com/");

        HttpResponse response = null;
        try {

            //add data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(      1);
            nameValuePairs.add(new BasicNameValuePair("username", "xxxxxxx"));
            nameValuePairs.add(new BasicNameValuePair("password", "xxxxx"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //execute http post
            response = httpclient.execute(httppost);



        } catch (Exception e) {
            Toast.makeText(mContext, e.getMessage(),Toast.LENGTH_LONG).show();
            flag = true;
            error = e.getMessage();
            e.printStackTrace();
        }

        try {
            return convertHttpResponseToString(response);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        if (flag) {
            Toast.makeText(mContext, "HttpHostConnectException Occured: " + error, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mContext, "DONE " + s.toString(), Toast.LENGTH_SHORT).show();
        }
    }


    private String convertHttpResponseToString(HttpResponse response) throws IOException {
        InputStream responseStream = response.getEntity().getContent();
        Scanner scanner = new Scanner(responseStream, "UTF-8");
        String responseString = scanner.useDelimiter("\\Z").next();
        scanner.close();
        return responseString;
    }


}
0

First of all switch to HttpURLConnection.

eg:-

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");

then try to get the string from InputStream.

Here is the working example.

   /**
     * Http post request that returns String as result(eg:- plain String or JSON String)
     * @param query is the request query
     *@return String that could be a plain String or JSON
     */
    public String connect_POST(final String query) throws IOException{

        HttpURLConnection con = (HttpURLConnection) new URL(_URL).openConnection();
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setDefaultUseCaches(false);
        con.setAllowUserInteraction(false);

        con.connect();

        OutputStream output = con.getOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(output);
        writer.write(query);
        writer.flush();
        output.close();
        writer.close();

        int responseCode = con.getResponseCode();
        Log.e("Request _URL : ", "" + _URL);
        Log.e("Request params : ", "" + query);
        Log.e("Response Code : ", "" + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String bufferString = response.toString();

        Log.e("bufferString : ", "" + bufferString);
        return bufferString;
    }
SRB Bans
  • 3,096
  • 1
  • 10
  • 21
0

Convert your returned result o JSONObject.

@Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(flag){
            Toast.makeText(mContext, "HttpHostConnectException Occured: "+error, Toast.LENGTH_SHORT).show();
        } else {
    if (s != null)
    {
        if (!s.equalsIgnoreCase(""))
        {
            JSONObject jsonobject = new JSONObject(s);
            // if its and array of data then convert it to json array
            JSONArray jsonArray = jsonObject.getJSONArray("name of the arry you are getting for example: 'Data'");
        }
    }
            Toast.makeText(mContext, "DONE "+s, Toast.LENGTH_SHORT).show();
        }

    }

    }
Amit Jangid
  • 2,741
  • 1
  • 22
  • 28
0

You are using String as return type. Use HttpResponse instead

1.extends AsyncTask<URL, String, HttpResponse>

2.change return type

@Override
        protected HttpResponse doInBackground(URL... data)

3.return response;

4.change argument type and get JSON object from the response

@Override
    protected void onPostExecute(HttpResponse s) {
        super.onPostExecute(s);
        if(flag){
            Toast.makeText(mContext, "HttpHostConnectException Occured: "+error, Toast.LENGTH_SHORT).show();
        } else {
            JSONObject jsonObject;
            JSONArray jsonArray = null;
            if (s != null)
            {
                try {
                    jsonObject = new JSONObject(s.toString());
                    jsonArray = jsonObject.getJSONArray("name of the arry you are getting for example: 'Data'");
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    e.printStackTrace();

            }
            Toast.makeText(mContext, "DONE "+jsonArray, Toast.LENGTH_SHORT).show();
        }

    }
piet.t
  • 11,718
  • 21
  • 43
  • 52
Jyoti JK
  • 2,141
  • 1
  • 17
  • 40
  • i got the same response – Giorgio Cafiso Apr 07 '18 at 07:56
  • convert the HTTPresponse as JSON – Jyoti JK Apr 07 '18 at 07:58
  • @Override protected void onPostExecute(HttpResponse s) { try { String json_string = EntityUtils.toString(s.getEntity()); JSONObject obj = new JSONObject(json_string);//you got JSON object from HTTP Response } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } IT CRASHES – Giorgio Cafiso Apr 07 '18 at 08:29
0

try executing your request (Found it here)

    // Execute HTTP Post Request
    ResponseHandler<String> responseHandler=new BasicResponseHandler();
    return httpclient.execute(httppost, responseHandler);

The request is causing the exception.

Vignesh KM
  • 1,979
  • 1
  • 18
  • 24