how to post json format data to server - android

How to post JSON data to .net server?
can i use:
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(URL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("Code", Code));
pairs.add(new BasicNameValuePair("Subject", Subject));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
httpResponse=httpClient.execute(httpPost);
or any other format to send json data?

You can create JSON Object and Put data into that object and pass it to the server..
use,
JSONObject json = new JSONObject();
json.put("UserName", "test2");
json.put("FullName", "1234567");
to put data into json object...
use
json.toString(); to send the data and
request.setHeader(HTTP.CONTENT_TYPE, "application/json");
to mark the json format...
Refer these links for more:
Send and Receive Json android-php
Sending json from Android

Here is the solution after referring many sources...
protected Void doInBackground(Void... params) {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(URL);
httpPost.setHeader("Content-Type", "application/json");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Code", Code);
jsonObject.put("Subject", Subject);
stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
httpResponse=httpClient.execute(httpPost);
return null;
}
protected void onPostExecute(Void result) {
//to see the response
httpEntity=httpResponse.getEntity();
Response=EntityUtils.toString(httpEntity);
System.out.println("Response "+Response);
int Response_Code = httpResponse.getStatusLine().getStatusCode();
System.out.println("Response_Code "+Response_Code);
}
Thanks for your response, also helped me find this.

You can add one more parameter to the URL named json(or any name you want), and use the json string as value and then get the json in your php.
example:
pairs.add(new BasicNameValuePair("Code", Code));
pairs.add(new BasicNameValuePair("Subject", Subject));
pairs.add(new BasicNameValuePair("Json", my_jsons_tring));

Related

Cant send json to server

I'm trying to send a json file to remote server. If I try it, using this site:
https://www.hurl.it/ passing a json like this:
it works. But If I try it from my code, I have some trouble.
ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
JSONArray list1 = new JSONArray();
list1.add("12345678");
Map obj=new LinkedHashMap();
obj.put("company_id","1");
obj.put("phones", list1);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
nameValuePairs1.add(new BasicNameValuePair("json", obj.toString()));
try {
URL url = new URL("http://crm.pavlun.info/api/register");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.setEntity(new StringEntity(nameValuePairs1.toString(), "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
HttpResponse response = httpClient.execute(httpPost);
Log.e("r ", response.toString());
}catch(Exception e) {
e.printStackTrace();
}
This is my json example: I need to create something like this: "json":{"company_id":"1","phones":["555555"],"photo":"/files/clients_photos/tmp/484629825.JPG","name":"sdfsdfdsf","birthdate":"10.02.2014", "email":"sdf#sdf.ff"}
UPD:
I have the following error:
{"status":"error","message":"Customer data is empty!"}
Maybe something is wrong in my json.
UDP:
working code
ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
JSONObject joB = new JSONObject();
JSONArray list1 = new JSONArray();
list1.add("258963147");
Map obj=new LinkedHashMap();
obj.put("company_id","1");
obj.put("phones", list1);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
org.json.JSONObject jsonqwe;
try {
JSONParser operationLink = new JSONParser();
ArrayList<NameValuePair> postP = new ArrayList<NameValuePair>();
postP.add(new BasicNameValuePair("json", JSONValue.toJSONString(obj)));
jsonqwe = operationLink.makeHttpRequest("http://crm.pavlun.info/api/register", "POST", postP);
Log.e("sad", jsonqwe.toString());
}catch(Exception e) {
e.printStackTrace();
}
You're problem is that you're not building a JSON object, but using the map's toString() method, which won't give you a properly formatted JSON object.
Try JSONObject's constructor that takes a map as parameter. And than call toString() on the JSONObject.
Try yo change
Map obj=new LinkedHashMap();
to
JSONObject obj=new JSONObject();
you need to send a JSON value
A more suitable solution would be to build a JSONObject instead of the Map you're using. Something like this:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONArray phoneNumbers = new JSONArray();
phoneNumbers.add("12345678");
JSONObject obj=new JSONObject();
obj.put("company_id","1");
obj.put("phones", phoneNumbers);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
nameValuePairs.add(new BasicNameValuePair("json", obj.toString()));
try {
URL url = new URL("http://crm.pavlun.info/api/register");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.setEntity(new StringEntity(nameValuePairs.toString(), "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
HttpResponse response = httpClient.execute(httpPost);
Log.e("r ", response.toString());
}catch(Exception e) {
e.printStackTrace();
}
This line will return garbage (as far server is concerned)
nameValuePairs1.toString()
because an ArrayList does implement toString like you are expecting. You should be using JSONArray/JSONObject instead.
In the hurl site example one name valu pair is sent. To send name value pais your content type should be form url encoded. So change:
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
to
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
Maybe this will help:
httpPost.setHeader("ENCTYPE","multipart/form-data");
EDIT:
As others already stated do not use a Map but a JSONObject. Then change
httpPost.setEntity(new StringEntity(nameValuePairs1.toString()));
to:
String nameValuPairsText = nameValuePairs.toString();
nameValuPairsText = nameValuPairsText.substring(1, nameValuPairsText.length()-1);
httpPost.setEntity(new StringEntity(nameValuPairsText, "UTF-8"));

send login details via POST from android

I am trying to send user email address and password from my android app to the db to login via POST.
On the server side, I get my data like this :
$email = $_POST['email'];
$password = clean($_POST['password'];
And on the android side I send it like so:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("some real URL");
httppost.setHeader("Content-type", "application/json");
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httppost);
......
Even when I type in valid login details, it fails and says no email address or password. Am I sending things across correctly?
I have also tried sending data across like below but didnt work. Any suggestions?
JSONObject obj = new JSONObject();
obj.put("email", email );
obj.put("password", password);
httppost.setEntity(new StringEntity(obj.toString()));
HttpPost.setEntity sets the body of the request without any name/value pairings, just raw post data. $_POST doesn't look for raw data, just name value pairs, which it converts into a hashtable/array. You can format the request such that it includes name value pairs.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("json", json.toString()));
httppost.setEntity(new UrlEncodedFormEntity(params));
And have the parameters in json object as:
JSONObject json = new JSONObject();
json.put("email", email );
json.put("password", password);
On the server side you can get the data as:
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
if( !empty($jsonObj)) {
try {
$email = $jsonObj['email'];
$password = $jsonObj['password'];
}
}

Android POST JSON OBJECT - How to set $_POST Index

i have a JSONObject which i want to POST to a server.
Here is the Code:
JSONObject obj = new JSONObject();
for(int k = 0; k<len;k++){
obj.put("nachrichten_ids", params[k]);
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("xxxxx");
HttpEntity entity;
StringEntity s = new StringEntity(obj.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = s;
httpPost.setEntity(entity);
HttpResponse response;
response = httpClient.execute(httpPost);
By doing Log.i("TEST",obj) i get the JSON object:
{"nachrichten_ids":"[2144,2138]"}
That data is send to the server. But i cant access it:
There is no $_POST index. (PHP)
How to set a index, so that i can access the json object, like $_POST['nachrichten_ids'].
I had to work with that data then e.g with php json_decode()
Any idea ?
Thanks
Try putting your jSON object into a namevaluepair. The name of the pair you add is the name you should use when reading it on the web. For example here I will get Password by calling $_POST['Password'].
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Password", "My password"));
nameValuePairs.add(new BasicNameValuePair("Mail", "My mail"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
BasicHttpResponse response = (BasicHttpResponse) httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

Create this string exactly in Android

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

how to post data using JSON for httpPost in Android

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

Categories

Resources