Post JSON on Android

Asked

Viewed 2,643 times

1

I wonder if android is yes or no performing my JSON post. Follows the code:

public void login(JSONObject dados) {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost hp = new HttpPost();

        hp.setURI(URI.create("http://10.0.2.2/restq/pages/salas"));
        hp.setHeader("Accept", "application/json");
        hp.setHeader("Content-type", "application/json");

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("json", dados.toString()));

        hp.setEntity(new StringEntity(dados.toString()));

        HttpResponse response = client.execute(hp);

        HttpEntity entity = response.getEntity();

        InputStream instream = entity.getContent();

        String resp = new Scanner(instream, "UTF-8").next();
        JSONObject jo = new JSONObject(resp);

        Log.d("JSON Retorno", jo.toString());
    }
}
  • You cannot get this information through the object response?

1 answer

3


Yes, you are making an HTTP request using the POST method.

To check what is being sent in the request you can use some tools, such as Requestbin, it collects the requisition information and lets you inspect what is being sent.

An interesting point to note, is that since you are not using the variable pairs, you could remove it from your code, getting like this:

public String post(final JSONObject data) {
    try {
        final HttpClient client = new DefaultHttpClient();
        final HttpPost httpPost = new HttpPost();

        httpPost.setURI(URI.create("http://requestb.in/1e4rp5p1"));
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        httpPost.setEntity(new StringEntity(data.toString()));

        final HttpResponse httpResponse = client.execute(httpPost);
        final HttpEntity entity = httpResponse.getEntity();
        final InputStream stream = entity.getContent();
        return new Scanner(stream, "UTF-8").next();
    } catch (Exception e) {
        Log.e("Your tag", "Error", e);
    }

    return null;
}

Another point to note is that the class DefaultHttpClient is deprecated from API 22. That said, I recommend you use the class URLConnection:

public String post(final JSONObject data) {
    try {
        final URL url = new URL("http://requestb.in/1e4rp5p1");
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-type", "application/json");

        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);

        final OutputStream outputStream = connection.getOutputStream();
        final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

        writer.write(data.toString());
        writer.flush();
        writer.close();
        outputStream.close();

        connection.connect();

        final InputStream stream = connection.getInputStream();
        return new Scanner(stream, "UTF-8").next();
    } catch (Exception e) {
        Log.e("Your tag", "Error", e);
    }

    return null;
}

You can also use libraries to simplify this part like Okhttp, Volley or even Retrofit.

An example of using the Okhttp library:

public String post(final JSONObject data) {
    try {
        final RequestBody body = RequestBody
                .create(MediaType.parse("application/json"), data.toString());
        final Request request = new Request.Builder()
                .url("http://requestb.in/1e4rp5p1")
                .post(body)
                .addHeader("Accept", "application/json")
                .build();
        final OkHttpClient client = new OkHttpClient();
        final Response response = client.newCall(request).execute();
        return response.body().string();
    } catch (Exception e) {
        Log.e("Your tag", "Error", e);
    }

    return null;
}

Remembering that in none of the above examples is done the status check of the request, and that the class is treated Exception, where it is interesting that only specific exceptions such as Ioexception.

I hope I’ve helped.

  • Peter, thanks for your help. I think I’m doing something wrong because I tried it both ways above and I tried to return the $_REQUEST from php to see if something came back. But every time he returns empty.

  • After all, you gave me the answer. I used the Okhttp library and tested if I was sending something by post. The result was that you passed the data by post. I adjusted PHP to get file_get_contents instead of $_REQUEST and it worked. Thank you so much for your help

  • I’m glad I could help! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.