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.
You cannot get this information through the object
response
?– Woss