How to Send Post Request in Json Using Httpclient in Android

How to send POST request in JSON using HTTPClient in Android?

In this answer I am using an example posted by Justin Grammens.

About JSON

JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name and like this object['name'];. The example from the article uses this bit of JSON.

The Parts

A fan object with email as a key and foo@bar.com as a value

{
fan:
{
email : 'foo@bar.com'
}
}

So the object equivalent would be fan.email; or fan['email'];. Both would have the same value
of 'foo@bar.com'.

About HttpClient Request

The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.

public static HttpResponse makeRequest(String path, Map params) throws Exception 
{
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();

//url with the post data
HttpPost httpost = new HttpPost(path);

//convert parameters into JSON object
JSONObject holder = getJsonObjectFromMap(params);

//passes the results to a string builder/entity
StringEntity se = new StringEntity(holder.toString());

//sets the post request as the resulting string
httpost.setEntity(se);
//sets a request header so the page receving the request
//will know what to do with it
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");

//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
return httpclient.execute(httpost, responseHandler);
}

Map

If you are not familiar with the Map data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.

private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {

//all the passed parameters from the post request
//iterator used to loop through all the parameters
//passed in the post request
Iterator iter = params.entrySet().iterator();

//Stores JSON
JSONObject holder = new JSONObject();

//using the earlier example your first entry would get email
//and the inner while would get the value which would be 'foo@bar.com'
//{ fan: { email : 'foo@bar.com' } }

//While there is another entry
while (iter.hasNext())
{
//gets an entry in the params
Map.Entry pairs = (Map.Entry)iter.next();

//creates a key for Map
String key = (String)pairs.getKey();

//Create a new map
Map m = (Map)pairs.getValue();

//object for storing Json
JSONObject data = new JSONObject();

//gets the value
Iterator iter2 = m.entrySet().iterator();
while (iter2.hasNext())
{
Map.Entry pairs2 = (Map.Entry)iter2.next();
data.put((String)pairs2.getKey(), (String)pairs2.getValue());
}

//puts email and 'foo@bar.com' together in map
holder.put(key, data);
}
return holder;
}


Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.

(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)

Update

I just happend to get a comment about how to use the code and realized that there was a mistake in the return type.
The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature
to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse
the path variable is the url and I updated to fix a mistake in the code.

Using HttpClient and HttpPost in Android with post parameters

have you tried doing it without the JSON object and just passed two basicnamevaluepairs?
also, it might have something to do with your serversettings

Update:
this is a piece of code I use:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate));

try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(connection);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("HTTP", "HTTP: OK");
} catch (Exception e) {
Log.e("HTTP", "Error in http connection " + e.toString());
}

How to send a JSON object over HttpClient Request with Android?

I do this with

httppost.setHeader("Content-type", "application/json");

Also, the new HttpPost() takes the web service URL as argument.

Sending a JSON POST request in Android

This repo is fairly good and has got all sort of http requests.
https://github.com/loopj/android-async-http

Send JSON as a POST request to server by AsyncHttpClient

I solved it, by adding header information to my entity object.

ByteArrayEntity entity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

Sending json object via http post method in android

Define a class AsyncT and call it in onCreate method using:

AsyncT asyncT = new AsyncT();
asyncT.execute();

Class definition:

class AsyncT extends AsyncTask<Void,Void,Void>{

@Override
protected Void doInBackground(Void... params) {

try {
URL url = new URL(""); //Enter URL here
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST"); // here you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
httpURLConnection.connect();

JSONObject jsonObject = new JSONObject();
jsonObject.put("para_1", "arg_1");

DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

return null;
}


}

How to send a JSON object over POST Request with Android

you are using PHP on the server side, so your HTTP entity must be a multipart encoded one. See this link. You are using a string entity, but this is not correct. It must be a MultipartEntity, which emulates what the browser does when you submit a form in a web page. MultipartEntity should be in httpmime jar.

Once you have your multipart entity, simply add a Part named "json", and set its contents to the string representation of your json-encoded object.

Note that this answer is because you use PHP on the server side, so you must use its "protocol" to read variables via $_REQUEST. If you used your own request parser oh the server side, even a StringEntity could be ok. See HTTP_RAW_POST_DATA

How to send JSON raw via POST Request on Android API Level 22

OK Now I know.. Requesting HTTP Type Request must be on a AsyncTask. not on the current thread because it will throw an exception when not on a Asynchronous Class due to Network Threading Exception. I forgot what the Exception is called. I'am only a beginner on Java. because I'am not really a Java programmer.

Here is the code to help others on this kind of problem.

public class REST extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection=null;
String json = null;
// The Username & Password
final EditText em = (EditText) findViewById(R.id.Username);
String email = (String) em.getText().toString();
final EditText pw = (EditText) findViewById(R.id.Password);
String password = (String) pw.getText().toString();
// -----------------------

try {
HttpResponse response;
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("email", email);
jsonObject.accumulate("password", password);
json = jsonObject.toString();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://cloudspecinc.herokuapp.com/api/user/login/");
httpPost.setEntity(new StringEntity(json, "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
httpPost.setHeader("Accept-Language", "en-US");
response = httpClient.execute(httpPost);
String sresponse = response.getEntity().toString();
Log.w("QueingSystem", sresponse);
Log.w("QueingSystem", EntityUtils.toString(response.getEntity()));
}
catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());

} finally {
/* nothing to do here */
}
return null;
}

@Override
protected void onPostExecute(Void result) {
if (result != null) {
// do something
} else {
// error occured
}
}
}


Related Topics



Leave a reply



Submit