How to send a JSON object over POST Request with Android - android

I am trying to build a small application in which the application will communicate with a php script with the help of JSON objects. I successfully implemented the GET Request test application but using JSON with post is creating problems. The code generates no error but my php script reply with no nothing except an empty Array() which implies that nothing was sent over the connection with code:
<?php print_r($_REQUEST); ?>
and trying with
<?php print($_REQUEST['json']); ?>
throws HTML back to the application with json variable not found error.
I have already tried a few solutions mentioned here including: How to send a JSON object over Request with Android? and How to send a json object over httpclient request with android so it would be great if you can point out my mistake and can briefly describe what exactly I was doing wrong. Thanks.
Here is the code snippet for from where the JSON Object is converted into string and then attached to a Post variable.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(wurl);
StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppostreq.setEntity(se);
//httppostreq.setHeader("Accept", "application/json");
//httppostreq.setHeader("Content-type", "application/json");
//httppostreq.setHeader("User-Agent", "android");
HttpResponse httpresponse = httpclient.execute(httppostreq);
HttpEntity resultentity = httpresponse.getEntity();
Here is TCP Stream Dump collected through wireshark if it can help:
POST /testmysql.php?test=true HTTP/1.1
Content-Length: 130
Content-Type: application/json;charset=UTF-8
Content-Type: application/json;charset=UTF-8
Host: 192.168.100.4
Connection: Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)
{"weburl":"hashincludetechnology.com","header":{"devicemodel":"GT-I9100","deviceVersion":"2.3.6","language":"eng"},"key":"value"}HTTP/1.1 200 OK
Date: Mon, 30 Apr 2012 22:43:10 GMT
Server: Apache/2.2.17 (Win32)
Content-Length: 34
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
Array
(
[test] => true
)
Test // echo statement left intentionally.

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

The below should work. Make sure to set the appropriate keys for what your form post is expecting at the top. Also I included how to send an image as well as other various json data, just delete those lines if that is not necessary.
static private String postToServerHelper(
String action,
JSONObject jsonData,
byte[] imageData){
// keys for sending to server
/** The key for the data to post to server */
final String KEY_DATA = "data";
/** The key for the action to take on server */
final String KEY_ACTION = "action";
/** The return code for a successful sync with server */
final int GOOD_RETURN_CODE = 200;
/** The key for posting the image data */
final String KEY_IMAGE = "imageData";
/** The image type */
final String FILE_TYPE = "image/jpeg";
/** The encoding type of form data */
final Charset ENCODING_TYPE = Charset.forName("UTF-8");
// the file "name"
String fileName = "yourFileNameHere";
// initialize result string
String result = "";
// initialize http client and post to correct page
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.yourdomain.com/yourpage.php");
// set to not open tcp connection
httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
// build the values to post, the action and the form data, and file data (if any)
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try{
multipartEntity.addPart(KEY_ACTION, new StringBody(action, ENCODING_TYPE));
multipartEntity.addPart(KEY_DATA, new StringBody(jsonData.toString(), ENCODING_TYPE));
if (imageData != null){
multipartEntity.addPart(KEY_IMAGE, new ByteArrayBody(imageData, FILE_TYPE, fileName));
}
}catch (Exception e){
return e.getMessage();
}
// set the values to the post
httpPost.setEntity(multipartEntity);
int statusCode= -1;
// send post
try {
// actual send
HttpResponse response = client.execute(httpPost);
// check what kind of return
StatusLine statusLine = response.getStatusLine();
statusCode = statusLine.getStatusCode();
// good return
if (statusCode == GOOD_RETURN_CODE) {
// read return
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
content.close();
result = builder.toString();
// bad return
} else {
return String.parse(statusCode);
}
// different failures
} catch (ClientProtocolException e) {
return e.getMessage();
} catch (IOException e) {
return e.getMessage();
}
// return the result
return result;
}

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
JSONObject clientList = new JSONObject ();
clientList.put("name","");
clientList.put("email","");
clientList.put("status","");
clientList.put("page","");
JSONObject listclient = new JSONObject ();
listclient.put("mydetail", clientList);
//--List nameValuePairs = new ArrayList(1);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("token", tokenid));
nameValuePairs.add(new BasicNameValuePair("json_data", listclient.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("JSON",nameValuePairs.toString());
//-- Storing Response
HttpResponse httpResponse = httpClient.execute(httpPost);

Related

Set UTF-8 for Vietnamese Android

I need to send string (vietnamese) from Android devices to server like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.URL.UPDATE_CURRENT_STATUS);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("location", "Thạch thất Hanoi "));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int respnseCode = response.getStatusLine().getStatusCode();
if (respnseCode == 200) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
But when server gets the string, its not like
Thạch thất Hanoi
its become
Thạch Thất Hanoi
My code in server side:
#RequestMapping(value = "/UpdateCurrentStatus", method = RequestMethod.POST, produces = { "application/json" })
#ResponseBody
public MessageDTO updateCurrentStatus(
#RequestParam Map<String, String> requestParams) throws TNException {
String location = requestParams.get("location");
System.out.println(location);
MessageDTO result = driverBO.updateCurrentStatus(location);
return result;
}
How can I resolve this problem? Thank you.
Did you set you android httpclient Content-Type header to application/json; charset=utf-8 instead of "application/json"?
I think your problem is that the content entity location you sent is encoded correctly in UTF-8 but server failed to acknowledge UTF-8. clarify it in Content-Type header.
You can diagnose http content and its header with great http monitoring tool Fiddler.
-EDIT BELOW-
Relace your UrlEncodedFormEntity as below. Set header to application/json; charset=utf-8 as I described earlier. it's good to set it up still.
JSONObject jsonParam = new JSONObject();
jsonParam.put("location", "Thạch thất Hanoi ");
StringEntity entity = new StringEntity(jsonParam.toString(), "UTF-8");
httppost.setEntity(entity);

Android post data via url

in my app i need to post data to an url to register a new user. Here is the url
http://myurl.com/user.php? email=[EMAIL]&username=[USERNAME]&password[PASS]&img_url=[IMG]
If I do that correctly I should get this message:
{"success":true,"error":null}
or if not {"success":false,"error":"parameters"}
Can somebody guide me through this and tell me how can I do it.
first :
you need to perform all network tasks in an Async thread using:
public class PostData extends AsyncTask<String, Void, String>{
{
#Override
protected String doInBackground(String... params) {
//put all your network code here
}
Second:
create your http request:
i am assuming email, username and IMG as variables over here.
String server ="http://myurl.com/user.php? email=[" + EMAIL + "]&username=[" + USERNAME + "]&password[" + PASS + "]&img_url=["+IMG + "]";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(server);
//httppost.setHeader("Accept", "application/json");
httppost.setHeader("Accept", "application/x-www-form-urlencoded");
//httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
third:
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("JSONdata", Object));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
try {
HttpResponse response =httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Now simple query your response handler i.e. response in this case.
Don't forget to add INTERNET permission in your androidManifest.xml
Hope this helps!
Use a HTTP client class, and format your URL via a specific URI constructor. Create a HTTP post, optionally set the entity, headers, etc, execute the post via the client, receive a HTTP response, pull the entity out of the response and process it.
EDIT for example:
HttpClient httpclient = new DefaultHttpClient();
URI uri = new URI("http",
"www.google.com", // connecting to IP
"subpath", // and the "path" of what we want
"a=5&b=6", // query
null); // no fragment
HttpPost httppost = new HttpPost(uri.toASCIIString);
// have a body ?
// post.setEntity(new StringEntity(JSONObj.toString()));
// post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
Reader r = new InputStreamReader(entity.getContent());
// Do something with the data in the reader.

Error in HttpPost.addheader in rest api call for android

This is my code . I am trying to do a post on the rest Api from android (API 10)
HttpPost httpPost = new HttpPost(
"http://www.reactomews.oicr.on.ca:8080/ReactomeRESTfulAPI/RESTfulWS/queryHitPathways");
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type"," text/plain; charset=UTF-8");
httpPost.addHeader("","PPP2R1A,CEP192,AKAP9,CENPJ,CEP290,DYNC1H1");
try {
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
System.out.println(statusCode);
Log.e(Gsearch.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
I just don't know what to add (as the first string)in the last addHeader method ! I tried "name", "ID" etc. Its not listed in the API too. The API documentation is here : http://reactomews.oicr.on.ca:8080/ReactomeRESTfulAPI/ReactomeRESTFulAPI.html
I tried to use firebug to see the post request in browser but it says post data = "PPP2R1A,CEP192,AKAP9,CENPJ,CEP290,DYNC1H1" .
Right now I am using "body" in there and I am getting a json respnse of length 0 . But if i try on browser from the documentation link , I get a json response. so the error is in the addHeader part.
The problem is your assumption that the data should be part of the header, because it shouldn't. If I run the sample request from the API through a random webproxy, I can see the following headers:
POST /ReactomeRESTfulAPI/RESTfulWS/queryHitPathways HTTP/1.1
Host reactomews.oicr.on.ca:8080
Content-Length 41
Accept application/json
Origin http://reactomews.oicr.on.ca:8080
User-Agent Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Content-type text/plain
Referer http://reactomews.oicr.on.ca:8080/ReactomeRESTfulAPI/ReactomeRESTFulAPI.html
Accept-Encoding gzip,deflate,sdch
Accept-Language nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.3
In other words: none of the "PPP2R1A,CEP192,AKAP9,CENPJ,CEP290,DYNC1H1" strings are there. In stead, that data is part of the post body, or the 'entity' that you can set to the post method.
Something like this should probably do it:
// creating of HttpPost omitted
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type"," text/plain; charset=UTF-8");
StringEntity entity = new StringEntity("PPP2R1A,CEP192,AKAP9,CENPJ,CEP290,DYNC1H1");
httpPost.setEntity(entity);
// execute post and get result etc.

Posting to Ruby on Rails app from android

So I am trying to post to a rails app from an Android app I am writing. I am able to post successful from inside the rails app. I was also able to post successfully using a chrome add on called Simple Rest client.
When I try and post from the Android app its hitting the rails app but creating an empty post. None of the input data is being received by rails.
I read that 3rd party applications are only able to GET from a Rails app depending on authentication so to make sure this wasn't the issue I was having I added this to my Rails config.
# de-activate tolken auth
config.action_controller.allow_forgery_protection = false
At this point I am unsure as to where my issue lies, with my Rails backend or my Android client.
ok so the Rails post method in my controller that I'm trying to reach is here
# POST /orders
# POST /orders.json
def create
#order = Order.new(params[:order])
respond_to do |format|
if #order.save
format.html { redirect_to #order, notice: 'Order was successfully created.' }
format.json { render json: #order, status: :created, location: #order }
else
format.html { render action: "new" }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
Here is the Android java code for sending the Post Request.
This is the method passing in the User input data I am trying to POST
private void postInformationtoAPI() {
showToast("POSTING ORDER");
List<NameValuePair> apiParams = new ArrayList<NameValuePair>();
apiParams.add(new BasicNameValuePair("drinks_id", GlobalDrinkSelected));
apiParams.add(new BasicNameValuePair("name", GlobalEditTextInputName));
apiParams.add(new BasicNameValuePair("paid" , GlobalIsPaid));
bgtPost = new BackGroundTaskPost(MAP_API_URL_POST_ORDER, "POST", apiParams);
bgtPost.execute();
goToOrderCompleted();
}
And this is the class that it is passed to, permorming the HTTP POST.
public class BackGroundTaskPost extends AsyncTask<String, String, JSONObject> {
List<NameValuePair> postparams = new ArrayList<NameValuePair>();
String URL = null;
String method = null;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public BackGroundTaskPost(String url, String method, List<NameValuePair> params) {
this.URL = url;
this.postparams = params;
this.method = method;
for (int i = 0; i < postparams.size(); i++){
String test = postparams.get(i).toString();
Log.d("This is in the lisht:", test);
}
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if (method.equals("POST")) {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
httpPost.setEntity(new UrlEncodedFormEntity(postparams, HTTP.UTF_8));
Log.i("postparams : ", postparams.toString());
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils
.format(postparams, "utf-8");
URL += "?" + paramString;
HttpGet httpGet = new HttpGet(URL);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Log.i("Logging out *is* before beffered reader", is.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
Log.i("Logging out *is* after beffered reader", is.toString());
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.i("json: ",json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data TEST " + e.toString());
}
// return JSON String
return jObj;
}
}
This is the what log's out for postparams in the above class, so I know data is actually being sent
04-03 21:36:23.994: I/postparams :(690): [drinks_id=41, name=Dave, paid=True]
This is what Log Cat is showing as a response from the server
04-03 20:56:08.247: I/json:(690): {"created_at":"2013-04-03T20:56:06Z","drinks_id":null,"id":1351,"name":null,"paid":null,"served":null,"updated_at":"2013-04-03T20:56:06Z"}
I am really struggling to understand where the issue lies with this and have been stuck on it for quite awhile. Any insight would be much appreciated. And if any more information is needed just shout.
Edit: logs from server
This is a successful post from the simple REST client
2013-04-03T23:13:31+00:00 app[web.1]: Completed 200 OK in 15ms (Views: 8.7ms | ActiveRecord: 5.2ms)
2013-04-03T23:13:42+00:00 app[web.1]: Started POST "/orders.json" for 89.101.112.167 at 2013-04-03 23:13:42 +0000
2013-04-03T23:13:42+00:00 app[web.1]: Processing by OrdersController#create as JSON
2013-04-03T23:13:42+00:00 app[web.1]: Parameters: {"updated_at"=>nil, "drinks_id"=>51, "id"=>1021, "name"=>"Test", "paid"=>true, "served"=>nil, "created_at"=>nil, "order"=>{"drinks_id"=>51, "name"=>"Test", "paid"=>true, "served"=>nil}}
2013-04-03T23:13:43+00:00 heroku[router]: at=info method=POST path=/orders.json host=fyp-coffeeshop.herokuapp.com fwd="89.101.112.167" dyno=web.1 connect=1ms service=25ms status=201 bytes=138
2013-04-03T23:13:43+00:00 app[web.1]: Completed 201 Created in 15ms (Views: 0.6ms | ActiveRecord: 13.2ms)
This is from the android app posting
2013-04-03T22:56:45+00:00 app[web.1]: Started POST "/orders.json" for 89.101.112.167 at 2013-04-03 22:56:45 +0000
2013-04-03T22:56:45+00:00 app[web.1]: Processing by OrdersController#create as JSON
2013-04-03T22:56:45+00:00 app[web.1]: Completed 201 Created in 23ms (Views: 2.2ms | ActiveRecord: 16.3ms)
2013-04-03T22:56:45+00:00 heroku[router]: at=info method=POST path=/orders.json host=fyp-coffeeshop.herokuapp.com fwd="89.101.112.167" dyno=web.1 connect=4ms service=37ms status=201 bytes=138
You're setting a content-type of JSON but not actually sending JSON, you're sending standard POST url-encoded parameters.
You need to actually send a JSON object:
JSONObject params = new JSONObject();
params.put("drinks_id", GlobalDrinkSelected);
params.put("name", GlobalEditTextInputName);
params.put("paid", GlobalIsPaid);
StringEntity entity = new StringEntity(params.toString());
httpPost.setEntity(entity);
The problem is that when you're building the POST in Android you're over-writing the entity (the body). You initially set it and then you set it again, effectively clearing out what you already set.
This is correct:
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
But then a couple of lines later you over-write it with:
httpPost.setEntity(new StringEntity("UTF-8"));
So ditch that 2nd setEntity() call.
You can achieve what you're trying to do - setting the POST body in UTF-8 by tweaking your code like:
httpPost.setEntity(new UrlEncodedFormEntity(postparams, HTTP.UTF_8));

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

I'm trying to figure out how to POST JSON from Android by using HTTPClient. I've been trying to figure this out for a while, I have found plenty of examples online, but I cannot get any of them to work. I believe this is because of my lack of JSON/networking knowledge in general. I know there are plenty of examples out there but could someone point me to an actual tutorial? I'm looking for a step by step process with code and explanation of why you do each step, or of what that step does. It doesn't need to be a complicated, simple will suffice.
Again, I know there are a ton of examples out there, I'm just really looking for an example with an explanation of what exactly is happening and why it is doing that way.
If someone knows about a good Android book on this, then please let me know.
Thanks again for the help #terrance, here is the code I described below
public void shNameVerParams() throws Exception{
String path = //removed
HashMap params = new HashMap();
params.put(new String("Name"), "Value");
params.put(new String("Name"), "Value");
try {
HttpClient.SendHttpPost(path, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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.
Here is an alternative solution to #Terrance's answer. You can easly outsource the conversion. The Gson library does wonderful work converting various data structures into JSON and the other way around.
public static void execute() {
Map<String, String> comment = new HashMap<String, String>();
comment.put("subject", "Using the GSON library");
comment.put("message", "Using libraries is convenient.");
String json = new GsonBuilder().create().toJson(comment, Map.class);
makeRequest("http://192.168.0.1:3000/post/77/comments", json);
}
public static HttpResponse makeRequest(String uri, String json) {
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Similar can be done by using Jackson instead of Gson. I also recommend taking a look at Retrofit which hides a lot of this boilerplate code for you. For more experienced developers I recommend trying out RxAndroid.
I recommend using this HttpURLConnectioninstead HttpGet. As HttpGet is already deprecated in Android API level 22.
HttpURLConnection httpcon;
String url = null;
String data = null;
String result = null;
try {
//Connect
httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
//Write
OutputStream os = httpcon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.close();
os.close();
//Read
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Too much code for this task, checkout this library https://github.com/kodart/Httpzoid
Is uses GSON internally and provides API that works with objects. All JSON details are hidden.
Http http = HttpFactory.create(context);
http.get("http://example.com/users")
.handler(new ResponseHandler<User[]>() {
#Override
public void success(User[] users, HttpResponse response) {
}
}).execute();
There are couple of ways to establish HHTP connection and fetch data from a RESTFULL web service. The most recent one is GSON. But before you proceed to GSON you must have some idea of the most traditional way of creating an HTTP Client and perform data communication with a remote server. I have mentioned both the methods to send POST & GET requests using HTTPClient.
/**
* This method is used to process GET requests to the server.
*
* #param url
* #return String
* #throws IOException
*/
public static String connect(String url) throws IOException {
HttpGet httpget = new HttpGet(url);
HttpResponse response;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
//instream.close();
}
}
catch (ClientProtocolException e) {
Utilities.showDLog("connect","ClientProtocolException:-"+e);
} catch (IOException e) {
Utilities.showDLog("connect","IOException:-"+e);
}
return result;
}
/**
* This method is used to send POST requests to the server.
*
* #param URL
* #param paramenter
* #return result of server response
*/
static public String postHTPPRequest(String URL, String paramenter) {
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(URL);
httppost.setHeader("Content-Type", "application/json");
try {
if (paramenter != null) {
StringEntity tmp = null;
tmp = new StringEntity(paramenter, "UTF-8");
httppost.setEntity(tmp);
}
HttpResponse httpResponse = null;
httpResponse = httpclient.execute(httppost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream input = null;
input = entity.getContent();
String res = convertStreamToString(input);
return res;
}
}
catch (Exception e) {
System.out.print(e.toString());
}
return null;
}

Categories

Resources