Android POST JSON Array to Server - android

I am having problems trying to POST a JSON Array.
For my Android code, I pass the JSON Array into the server by doing:
interests = // JSONArray of JSONObjects
final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(PARAM_USERNAME, username));
params.add(new BasicNameValuePair(PARAM_INTERESTS, interests.toString()));
HttpEntity entity = new UrlEncodedFormEntity(params);
final HttpPost post = new HttpPost(UPDATE_INTERESTS_URI);
post.setEntity(entity);
// POST data to server
But when I read it from the server using:
$interests = $_POST["interests"];
echo $interets
It looks like [{\"a\":\"1\"},{\"b\":\"2\"}] instead of [{"a":"1"},{"b":"2"}]. The first one won't decode properly, and the second one works.
So why is it not working?
EDIT:
When I look at on Android before it posts, the JSONArray.toString() looks like [{"a":"1"},{"b":"2"}]

Don't know about android, but that looks like the magic quotes-feature of PHP is adding those slashes, if that's the case you could use this on server-side:
$interests = $_POST["interests"];
if (get_magic_quotes_gpc()) {
$interests = stripslashes($interests);
}
echo $interests;

do it in this way:
JSONObject paramInput = new JSONObject();
paramInput.put(PARAM_USERNAME, username);
paramInput.put(INTERESTS, interests.toString());
StringEntity entity = new StringEntity(paramInput.toString(), HTTP.UTF_8);

You can try to use:
StringEntity params = new StringEntity("your_Data");
instead of your UrlEncodedEntity.

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

json object post to php script in android app

I tried this android code for send json objects to my website
HttpPost httppost = new HttpPost(url);
JSONObject j = new JSONObject();
j.put("name","name ");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String format = s.format(new Date());
nameValuePairs.add(new BasicNameValuePair("msg",j.toString() ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
And this php code
<?php
$msg=$_POST["msg"];
$filename="androidmessages.html";
file_put_contents($filename,$msg."<br />",FILE_APPEND);
$androidmessages=file_get_contents($filename);
echo $androidmessages;
?>
It will show me {"name":"name "}
but if i use
httppost.setHeader( "Content-Type", "application/json" );
it will show nothing.I have no before experince about json object post but i think something went wrong.I want to send some user information to my website and display it in web page can you please tell me what i need to change to overcome this problem
Thank you
Finally i got the answer
$msg=json_decode(file_get_contents('php://input'), true);
$filename="androidmessages_json.html";
file_put_contents($filename,$msg['name']."<br />",FILE_APPEND);
$androidmessages=file_get_contents($filename);
echo $androidmessages;
It depends how you want to pass the data to your PHP-script.
If you want to get the JSON as a string in one variable (and maybe others in addition), then you should not use the content-type "application/json". If you want to only post the JSON without any variable, you can do the following instead:
HttpPost httppost = new HttpPost(url);
JSONObject j = new JSONObject();
j.put("name","name ");
httppost.setEntity(new StringEntity(j.toString());
httpclient.execute(httppost);
As you can imagine from the code you do not have the JSON in one POST-var only but in total.

How to send JSON object over request to web service in android

I would like to pass JSON object as request to web service like i mentioned below.
Result:{
"email":"xxxxxxx",
"password":"xxxxxx",
"Marks":[
{
"mark1":"50",
"mark2":"70"
}
],
"firstname":"xxxx",
"lastname":"xxxxx"
}
My code:
...
HttpPost httppost = new HttpPost("My Url");
httppost.setEntity(new StringEntity(**message**.toString(), "UTF-8"));
Here message should have json object in above format.How could i format JSON object?
Thanks.
If you arer having trouble in implementing above json object at android side then you can construct it like below,
JSONObject message = new JSONObject();
JSONObject mParams = new JSONObject();
mParams.put("email", "xxxx");
mParams.put("password", "xxx");
JSONArray markArray = new JSONArray();
JSONObject markObj = new JSONObject();
markObj.put("mark1", "50");
markObj.put("mark2", "70");
markArray.put(markObj);
mParams.put("Marks", markArray);
mParams.put("FirstName", "xxxx");
mParams.put("lastname", "xxxx");
message.put("Result",mParams);
Now in your code
HttpPost httppost = new HttpPost("My Url");
httppost.setEntity(new StringEntity(**message**.toString(), "UTF-8"));
You can just send it like a String:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", message.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
and
$data = json_decode($json);
First of all, the JSON which you have mentioned above is INVALID.
Now,
Here message should have json object in above format.How could i
format JSON object?
=> There are 2 ways to do that:
1) Create a request structure by using JSONObject or JSONArray classes, something like:
JSONObject objRequest = new JSONObject();
objRequest.putString("email","xxxx");
objRequest.putString("password","xxxx");
while setting entity inside HttpPost object, convert it into the String value.
2) Bad way, simple generate a string value with escape sequences, something like:
String strRequest = "{\"email\":\"xxxxxxx\",\"password\":\"xxxxxx\"}";
This may help you..Use GSON library. GSON is a Google library to parse JSON resources. With regards to the Marshalling, it basically means a way to translate data structures (like objects in an OOP language) to JSON... for instance:
// Java object
class Book {
private String title;
private String isbn;
private Set<author> authors;
}
#Entity
class Author {
private String firstName;
private String lastName;
}
To...
{title: "Vocation Createurs",
isbn: "2829302680",
authors: [{firstName: "Barbara", lastName: "Polla"},
{firstName: "Pascal", lastName: "Perez"}]}
You can also use existing libraries like android-json-rpc

passing an array of string using json

JSONObject jsonObj = new JSONObject();
jsonObj.put("email", email);
jsonObj.put("password", password);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost("http://api.readfa.st/session");
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);`
Currently I am working in an android project where i need to pass an array user[email], user[password] to a web page using json...please if any one can help me width this asap..Thank you!
I'm not sure what you mean. But I guess you need something like this:
JSONArray jsonArray = new JSONArray(listOfUsers);
String jsonRepresentationForListOfUsers = jsonArray.toString();
You can look here for further documentation.
http://developer.android.com/reference/org/json/JSONArray.html

How to use JSON for inserting records into SQL database

Let's say I store a list of names , for eg: "abc","bcd","gdf"... in an array of Strings. I have an Android app that displays each of those values along with a checkbox. I need to convert my String array into a JSON String so that I can store it in a remote database. Right now I am working on localhost with a database created using SQL Server. I need to insert the JSON string values in the database using a web service , preferably SOAP
How should I do this ? Is there any other better way to do so ?
Here is my Android code.
Thanks
In my case this works fine,
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", value1);
jsonObject.put("key2", value2);
JSONArray jArrayParam = new JSONArray();
jArrayParam.put(jsonObject);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("bulkdata",
jArrayParam.toString()));
Log.e("bulkdata", jArrayParam.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("yor remote database url");
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// get response entity
HttpEntity entity = response.getEntity();
Try it. Thnx.
Well, I just tried to show you how to write the String array to JSONObject and JSONArray.
String arr[] = {"1","parth","present","30-82011","Mumbai"};
try {
JSONObject obj=new JSONObject();
obj.put("rollno",new Integer(arr[0]));
obj.put("status",arr[1]);
obj.put("date",arr[2]);
obj.put("place",arr[3]);
System.out.print(obj.toString(1));
JSONArray list = new JSONArray();
list.put(arr[0]);
list.put(arr[1]);
list.put(arr[2]);
list.put(arr[3]);
System.out.print(list.toString(1));
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}
var arr:String = com.adobe.serialization.json.JSON.encode(Obj);
var data_projects:Array = stmt.getResult().data;
var b_data:String = com.adobe.serialization.json.JSON.encode(data_projects);
var arr:String = com.adobe.serialization.json.JSON.encode(data_projects);
var arr1:Object = com.adobe.serialization.json.JSON.decode(b_data) as Array;
 for(var d:int=0;d<=data_projects.length-1;d++)
 
{
//Mapping properties of Proxy classes with actual fields
var bbb:Object = new Object;
data.MdId = arr1[d].MD_ID;
data.MdDevId=arr1[d].MD_DEVICE_ID;
data.MdRecId=arr1[d].MD_REC_ID;
data.MdPrjId= arr1[d].MD_PRJ_ID ;
data.MdMbcId = arr1[d].MD_MBC_ID;
data.MdMbcValue= arr1[d].MD_MBC_VALUE;
data.MdParentRecId= arr1[d].MD_MBC_ID;
//below is the create method on the WSDL
ws.Create(data);
}

Categories

Resources