Using HttpClient and HttpPost in Android with post parameters
Solution 1
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());
}
Solution 2
You can actually send it as JSON the following way:
// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
Patrick
Web developer working at one of Sweden's largest media companies. Backend mostly, but some frontend stuff as well. Daily work involves PHP, Zend Framework, MySQL, Javascript and CoffeeScript. Have previous experience in Java and Wicket. Likes to play around in Ruby and Python.
Updated on November 29, 2020Comments
-
Patrick over 3 years
I'm writing code for an Android application that is supposed to take data, package it as Json and post it to a web server, that in turn is supposed to respond with json.
Using a GET request works fine, but for some reason using POST all data seems to get stripped and the server does not receive anything.
Here's a snippet of the code:
HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 5000); DefaultHttpClient httpClient = new DefaultHttpClient(params); BasicCookieStore cookieStore = new BasicCookieStore(); httpClient.setCookieStore(cookieStore); String uri = JSON_ADDRESS; String result = ""; String username = "user"; String apikey = "something"; String contentType = "application/json"; JSONObject jsonObj = new JSONObject(); try { jsonObj.put("username", username); jsonObj.put("apikey", apikey); } catch (JSONException e) { Log.e(TAG, "JSONException: " + e); } HttpPost httpPost = new HttpPost(uri); List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new BasicNameValuePair("json", jsonObj.toString())); HttpGet httpGet = null; try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams); entity.setContentEncoding(HTTP.UTF_8); entity.setContentType("application/json"); httpPost.setEntity(entity); httpPost.setHeader("Content-Type", contentType); httpPost.setHeader("Accept", contentType); } catch (UnsupportedEncodingException e) { Log.e(TAG, "UnsupportedEncodingException: " + e); } try { HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { InputStream is = httpEntity.getContent(); result = StringUtils.convertStreamToString(is); Log.i(TAG, "Result: " + result); } } catch (ClientProtocolException e) { Log.e(TAG, "ClientProtocolException: " + e); } catch (IOException e) { Log.e(TAG, "IOException: " + e); } return result;
I think I have followed the general guidelines on how to create the parameters and post them, but apparently not.
Any help or pointers to where I can find a solution, are very welcome at this point (after spending a few hours realizing no post data was ever sent). The real server is running Wicket on Tomcat, but I've also tested it out on a simple PHP page, with no difference.
-
Patrick almost 13 yearsI tried passing just the two
BasicNameValuePairs
and still there seems to be no data sent as POST. Could it be that the request is sent as a get, thus no post data is handled by the server? HttpPost should make sure that's not happening, shouldn't it? -
Patrick almost 13 yearsSince I'm working in parallell with an Iphone developer, and his app actually posts data, I have no other choice than also submitting data as JSON. I tried sending just the two valuepairs, but no difference.
-
Patrick almost 13 yearsYep, that's much like the code I ended up with too, after removing the content-type setting (that I used way too much apparently), as mentioned in my comment to the original post. Thanks for the help.
-
htafoya almost 11 yearsThank you! Using namevaluepairs didn't work for me but this was just right.
-
Pankaj about 9 yearsWhat is the difference between UrlEncodedFormEntity and StringEntity. Does it take different settings on server? When to use UrlEncodedFormEntity and when to use StringEntity?
-
barbsan over 5 yearshow is this code related to the question? edit your answer and add explanation
-
FireTr3e about 2 yearsThis solution might not work on some sites because older ones do not accept json as a post request payload type.