I am doing an Android application and I have a problem doing my request against my own server. I have made the server with Play Framework, and I get the parameters from a Json:
response.setContentTypeIfNotSet("application/json; charset=utf-8");
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(getBody(request.body));
Long id =jsonElement.getAsJsonObject().get("id").getAsLong();
When I make my GET request against my server, all is ok. But when I make a POST request, my server return me an unknown error, something about there is a malformed JSON or that it is unable to find the element.
private ArrayList NameValuePair> params;
private ArrayList NameValuePair> headers;
...
case POST:
HttpPost postRequest = new HttpPost(host);
// Add headers
for(NameValuePair h : headers)
{
postRequest.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty())
{
postRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(postRequest, host);
break;
I have tried to do with the params of the request, but it was a failure:
if(!params.isEmpty())
{
HttpParams HttpParams = new BasicHttpParams();
for (NameValuePair param : params)
{
HttpParams.setParameter(param.getName(), param.getValue());
}
postRequest.setParams(HttpParams); }
And there is the different errors, depends on the request I make. All of them are 'play.exceptions.JavaExecutionException':
'com.google.gson.stream.MalformedJsonException'
'This is not a JSON Object'
'Expecting object found: "id"'
I wish somebody can help me.
Here is a simple way to send a HTTP Post.
HttpPost httppost = new HttpPost("Your URL here");
httppost.setEntity(new StringEntity(paramsJson));
httppost.addHeader("content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
You would be better off using the JSON String directly instead of parsing it here. Hope it helps
Try this,It may help u
public void executeHttpPost(String string) throws Exception
{
//This method for HttpConnection
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("URL");
List<NameValuePair> value=new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("Name",string));
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
request.setEntity(entity);
client.execute(request);
System.out.println("after sending :"+request.toString());
}
catch(Exception e) {System.out.println("Exp="+e);
}
}
Related
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);
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.
I want to build 2 same products for Android and iOs.
The iOs already works, but the android doesnt, that's because of the format of the string.
in iOs this is:
NSString*jsonString = [[NSString alloc] initWithFormat:#"{\"id\":\"%#\",\"longitude\":\"%#\",\"latitude\":\"%#\",\"timestamp\":\"%#\"}", _phonenumber, longitude , latitude, stringFromDate];
And i dont know how to do this exactely like this in android. The format here is different.
What i have now is:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("id", num));
nameValuePairs.add(new BasicNameValuePair("longitude", longi));
nameValuePairs.add(new BasicNameValuePair("latitude", lat));
nameValuePairs.add(new BasicNameValuePair("timestamp", time));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
Thanks in advance, i need this by the end of the week so if you could help me, that would be greatly appreciated
i get this as an result from the iOs string:
{
"id":"0612833398",
"longitude":"-143.406417",
"latitude":"32.785834",
"timestamp":"10-10 07:56"
}
Okay, this is what my problem is.
Yes i need to send this exact string to an asp.net file on a server. But i need to know how to combine this with this: with the http post to
HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php");
before i combined this with the nameValuePPairs like this
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Create same string as you are getting in IOS by create an JosnObject as:
JSONObject json = new JSONObject();
json.put("id", "0612833398");
json.put("longitude", "-143.406417");
json.put("latitude", "32.785834");
json.put("timestamp", "10-10 07:56");
now if you make a print for json object you will get this string :
{"id":"0612833398","longitude":"-143.406417","latitude":"32.785834",
"timestamp":"10-10 07:56"}
and Post JSONObject as to server :
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php");
httppost.setHeader("Content-type", "application/json");
// Create json object here...
JSONObject json = new JSONObject();
json.put("id", "0612833398");
json.put("longitude", "-143.406417");
json.put("latitude", "32.785834");
json.put("timestamp", "10-10 07:56");
/// create StringEntity with current json obejct
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
}
To create a String you can use String.format(). In this case the syntax is very similar to Objective-C:
String s = String.format("{\"id\":\"%s\",\"longitude\":\"%s\",\"latitude\":\"%s\",\"timestamp\":\"%s\"}", num, long, lat, time);
HTTP Post goes like this:
HttpPost postMethod = new HttpPost(url);
try {
HttpParams params = new BasicHttpParams();
params.setParameter(name, value);
postMethod.setParams(params);
httpClient.execute(postMethod);
} catch (Exception e) {
} finally {
postMethod.abort();
}
I have an example json as below:
{
"Passwd":"String content",
"Userme":"String content"
}
how to construct the JSON String as above and give it as argument to HttpPost in Android.?
Can anyone help me in sorting out this issue.
thanks in Advance,
You can make use of JSONObject to create a simple json like { "Passwd":"String content", "Userme":"String content" } try something like this.
String json="";
JSONObject jobj = new JSONObject();
jobj.put("Userme", "Username");
jobj.put("Passwd", "PasswordValue");
json = jobj.toString();
Above String can be sent as one of the parameter using HTTP POST easily. Below function takes url and json as parameters to make POST request.
private void httpPost(String json,String url) throws ClientProtocolException, IOException{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("json", json));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpClient.execute(httpPost);
}
I need to create an HTTP POST request with parameters. I know there are many examples out there, I have tried using HTTPparams, NameValuePair etc but cant seem to get the correct format for the server.
Server Type: REST based API utilizing JSON for data transfer
Content-type: application/json
Accept: application/json
Content-length: 47
{"username":"abcd","password":"1234"}
I can pass these headers but I cant seem to pass these params "username","password". Here is my code:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username","abcd"));
pairs.add(new BasicNameValuePair("password","1234"));
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,"UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
I tried to debug, but cant see if entity is attached properly or not... What am I doing wrong?
Thanks in Advance.
Maaz
Try this:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
obj.put("username", "abcd");
obj.put("password", "1234");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
I'm not quite sure, from your description, but it would seem that your server expects a JSON content object instead of the data being encoded in the URL. Send something like this as the body of your post:
{"username":"abcd","password":"1234"}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username","abcd"));
pairs.add(new BasicNameValuePair("password","1234"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse response = client.execute(post);
just try this coz it works perfect for me when i am trying to HTTP post.
this will probably work for you.
assuming you already have the json object.
NOTE: (1)in the server you need to handle th request as utf-8 (also in the DB).
#SuppressWarnings("unchecked")
private static HttpResponse executePostRequest(JSONObject jsonData, String url) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
try {
httpost.setEntity(new ByteArrayEntity(jsonData.toString().getBytes("UTF8")));
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json;charset=UTF-8");
httpost.setHeader("Accept-Charset", "utf-8");
HttpResponse httpResponse = httpclient.execute(httpost);
return httpResponse;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
then in the client handle the server response like this:
String responseBody = EntityUtils
.toString(response.getEntity(), "UTF-8");