Java – HttpGet with request body android

HttpGet with request body android… here is a solution to the problem.

HttpGet with request body android

I tried making a request on the server via HttpGet. But it should be a JSON object in the message body. The following code does not work because unit_id and sercret_key are not sent to the server in the body message. What should I do?

JSON object:

{
"unit_id": 12345,
"secret_key": "sdfadfsa6as987654754"
}

My code:

private HttpResponse makeRequest(int id, String secretKey) throws Exception {
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter("id", id);

params.setParameter("secret_key", secretKey);

httpget.setHeader("Accept", "application/json");

httpget.setParams(params);
    httpget.setHeader("Content-type", "application/json");

 Handles what is returned from the page
    return httpclient.execute(httpget);
}

EDIT: In PHP, this request is made like this

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://0101.apiary.io/api/reservations/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n    \"unit_id\": 12345,\n    \"secret_key\":     \"sdfadfsa6as987654754\"\n}");
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response = curl_exec($ch);
curl_close($ch);

var_dump($response);

Solution

Basically, you can’t use HTTP/GET requests to send row data in the body (JSON or anything). The protocol does not allow you to do this at all. Obviously, you also have to do this in Android using POST. 🙂

Update

I was wrong. In fact, the protocol does allow you to put an entity into a request object. You can use this class instead of Apache HttpGet.

public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {

public HttpGetWithEntity() {
        super();
    }

public HttpGetWithEntity(URI uri) {
        super();
        setURI(uri);
    }

public HttpGetWithEntity(String uri) {
        super();
        setURI(URI.create(uri));
    }

@Override
    public String getMethod() {
        return HttpGet.METHOD_NAME;
    }
}

Then use it like below

HttpClient client = new DefaultHttpClient();
HttpGetWithEntity myGet = new HttpGetWithEntity("Url here");
myGet.setEntity(new StringEntity("This is the body", "UTF8"));
HttpResponse response = client.execute(myGet);

Find the source of HttpGetWithEntity here

Related Problems and Solutions