pass data using http post [duplicate] - android

This question already has answers here:
Sending POST data in Android
(17 answers)
Closed 9 years ago.
i am making one application which should give response on the click of button like
-- REQUEST HEADERS --
User-Agent: XYZ
Host: root.url
Content-Type: application/json; charset=utf-8
Content-Length: 123
...
-- REQUEST BODY --
{
"Apikey": "abcdefgh-ijkl-mnop-qrst-uvwxyz12345",
"Imei": "0123456789012354"
"Gps": {
"Latitude": 1.23,
"Longitude": 4.56
},
// Request specifics go here
}
how to pass this data using http post method

hi check this answer :
https://stackoverflow.com/a/10410693/1168654
http://localtone.blogspot.in/2009/07/post-json-using-android-and-httpclient.html
create array like below and pass it in HttpPost method.
ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
nameValuePairs1.add(new BasicNameValuePair("user_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_review",""+text));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity entity = responce.getEntity();
is = entity.getContent();
BufferedReader bufr = new BufferedReader(new InputStreamReader(is1,"iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(bufr.readLine() + "\n");
String line = "0";
while ((line = bufr.readLine()) != null)
{
sb.append(line + "\n");
}
is1.close();
result = sb.toString();
that array pass with url and give you result.

As your web service expect JSONObject in a request, you can create and simple set it inside HTTPPost using setEntity().
For example:
JSONObject objRequest = new JSONObject();
objRequest.put("Apikey","abcdefgh-ijkl-mnop-qrst-uvwxyz12345");
objRequest.put("Imei","0123456789012354");
JSONObject objGps = new JSONObject();
objGps.put("Latitude",1.23);
objGps.put("Longitude",4.56);
objRequest.put(Gps, objGps);
Now, here is a way to call webservice using request data:
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost= new HttpPost(url);
post.addHeader("Content-Type", "application/json; charset=utf-8"); // addHeader()
httpPost.setEntity(new StringEntity(objRequest.toString(),"utf-8")); // request data
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}

Related

Android CouchDB {"error":"bad_request","reason":"invalid_json"}

While trying to Create a new Document in my IrisCouch Database, i am always getting following error:
{"error":"bad_request","reason":"invalid_json"}
This is the relevant part of my function:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://username.iriscouch.com:6984/mydb");
StringEntity entity = new StringEntity(body);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.toString()) ;
HttpEntity httpEntity = httpResponse.getEntity();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
System.out.println("body: " + body);
} catch (Exception e) {
e.printStackTrace();
}
Here is my System.out of "body":
{"bild1":"","bild2":"","bild3":"","bild4":"","bild5":"","bild6":"","bild7":"","bild8":"","bild9":"","bild10":"","name":"","plz":0,"ort":"","strasse":"","n_koordinate":0,"e_koordinate":0,"beschreibung":"","groesse":"< 50m²","sitzplaetze":"< 50","grillstellen":"1","reservierung":false,"res_name":"","res_tele":"","res_weiteres":"","wc":true,"behindi":false,"dach":true,"kinderfreundl":false,"auto":false,"kinderwagen":false,"einkauf":false,"datum":"2015-07-01-14:12:01:856","bewertung":0,"anz_bewertung":0}
The JSON is valid. Tested it with jsonlint.com JSON Validator.
What could i do? Thanks in advance!
Perhaps the unicode superscript 2 (²) is bothering it?
Not sure which library this HttpPost is, but seems a lot like the HttpWebRequest, so try setting your header this way:
httpPost.setHeader("Content-type", "application/json charset=utf-8");
It could also be that the HttpPost class doesn't properly encode strings.
(I haven't pasted this in my Visual studio, so just a shot in the dark)

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);

500 Internal Server Error by post request android

Will HTTP post request cause 500 internal server ERROR?. hmmm if so below is my code and why am i constantly getting 500 Internal server error? what am i missing in the code?.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost((GetAllNewsURL));
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("pageNo", "0"));
nameValuePairs.add(new BasicNameValuePair("newsPerPage",
"0"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
stream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
thanks,
for me sometimes because of problem on server side I have to send params as header try the same thing like
HttpPost httppost = new HttpPost((GetAllNewsURL+"?pageNo=0&newsPerPage=0"));
or only pass one param as header hopefully it works

How to pass header to WebView in Android [duplicate]

This question already has answers here:
Send Post request along with HttpHeaders on Android
(2 answers)
Closed 2 years ago.
I am passing post data as Json using postUrl() to WebView in Android. Now I want to pass a header "Content-Type: application/json" also along with that. How to achieve it?
may this will help u :)
HttpPost httpPost = new HttpPost(url_src);
HttpParams httpParameters = new BasicHttpParams();
httpclient.setParams(httpParameters);
StringEntity se = new StringEntity(str,"UTF-8");
se.setContentType("application/json");
httpPost.setEntity(se);
httpPost.setHeader("userId", ""+userId);//userID
httpPost.setHeader("machineId", machineId);//deviceUserMachineID
response = httpclient.execute(httpPost);
I believe this will help: link
Doesn't look like you can actually send headers with postUrl(), only with loadUrl() method.
it possible to post data with header i have done it in my project
I am posting you my code ...
HttpParams par = new BasicHttpParams();
//par.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
int timeoutConnection = 30000;
HttpConnectionParams.setConnectionTimeout(par, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(par, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(par);
// httpClient.setParams(par);
HttpPost httpPost = new HttpPost(url);
httpPost = new HttpPost(url);
if(postMessage==null)
throw new IllegalArgumentException("please send post data as well");
byte[] data =postMessage.toString().getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
System.out.println("Base64: "+base64);
// httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setEntity(new StringEntity(base64));
httpPost.setHeader("token", app.getToken());
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
System.out.println("httpEntity.getContent():"+ is );
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
data = sb.toString();
//remember httpconnection should be in background thread
// if you use asynchtask then upper code should be in doinbackground method
//and in onpostexecution do data load in webview
webview.loadData(data, "text/html","UTF-8");

What is wrong with this POST request with json on android?

I'm trying to perform a POST request to a server that wants the Content-Type set to application/json with name and email as some keys. Currently, I'm getting a 406 error, which I'm assuming is working on the server side, but android can't handle the response. How can I tweak the code to get a 200 response?
HttpClient client = new DefaultHttpClient();
HttpEntity entity;
try{
JSONObject j = new JSONObject();
j.put("name" , myName);
j.put("email", myEmail);
HttpPost post = new HttpPost(targetURL);
post.setHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(j.toString(), HTTP.UTF_8);
se.setContentType("application/json");
post.setEntity(se);
HttpResponse response = client.execute(post);
entity = response.getEntity();
Log.d("response", response.getStatusLine().toString());
} catch(Exception e){Log.e("exception", e.toString());}
Does that look about right? Do I need one of those response handlers when creating the HttpClient?
This works for me with json-2.0.jar
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), MyApplication.HTTP_TIMEOUT); //Timeout Limit
HttpResponse response;
ArrayList<appResults> arrayList = new ArrayList<appResults>();
String resul;
try{
HttpGet get = new HttpGet(urls[0]);
response = client.execute(get);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
resul = convertStreamToString(in);
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<appResults>>() {}.getType();
arrayList = gson.fromJson(resul, listType);
in.close();
of course in asynctask or thread.
But 406... it seems that your format on your webserver and your app are not consistent...

Categories

Resources