Igor
Igor

Reputation: 1311

What is the preferable method for sending request in mobile API in Rails

I have created an API controller to handle only json requests from an Android app. Naturally I'm using token authentication. What would be better: To send a request using POST:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.170:3000/api/get_all");
httppost.setHeader("content-type", "application/json; charset= utf-8");
httppost.setHeader("Accept", "application/json");
JSONObject json = new JSONObject();
json.put("token", token);
StringEntity entity = new StringEntity(json.toString(), "utf-8");
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);

or GET:

httpget = new HttpGet("http://10.0.0.170:3000/api/get_all?"+"token="+token);
httpget.setHeader("content-type", "application/json; charset= utf-8");
httpget.setHeader("Accept", "application/json");
response = httpclient.execute(httpget);
result = EntityUtils.toString(response.getEntity());

clearly there is less code in GET, but is there some other reasons to prefer one over the other?

Upvotes: 0

Views: 176

Answers (1)

Alex P
Alex P

Reputation: 1751

Even if you are using this token for simple lookup, i.e. without changing the state on server, use POST. If you use GET, web server will log all query parameters making it more vulnerable for log injection attacks for example.

You should also consider using HTTPS for authentication token in production. In your code consider also handling return status from web server (e.g. when it is not 200).

In general, for the choice POST vs GET you can also refer to W3C:

Use GET if:

  • The interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).

Use POST if:

  • The interaction is more like an order, or
  • The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or
  • The user be held accountable for the results of the interaction.

Upvotes: 1

Related Questions