I am sending JSONObject to the server using below code. But I am unable to receive it in server side using PHP . Can anyone please guide me how to receive it.
public void sendStatus(JSONObject object) {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams);
String jsonString = object.toString();
try {
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(jsonString);
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) {
} catch (IOException e) {
}
}
I have already done it using name value pair using following code
$datastring = trim($headers['name']);
But as in the above code I am only getting the JSONObject but not any tag. So please anyone can help me or provide me any useful link then I will be grateful.
My JSONObject format is as belos=w
{
"user_id": "123456",
"Objects": [
{
"name": "AAA"
},
{
"name": "BBB"
},
{
"name": "CCC"
},
{
"name": "DDD"
}
]
}
To send the JSON as string from the Android device you can send it as a POST param:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json_string", jsonString));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
or if you want to send it as a header:
httppost.addHeader("json_string", jsonString)
However, a header has a maximum length so I'd recommend sending it as POST params
In order to work with a JSON object in PHP, you must decode it first into a associative array doing the following
$jsonAsArray = json_decode($jsonAsString, true)
Afterward, you'll be able to access JSON properties like:
$jsonAsArray['user_id'] // 123456
$jsonAsArray['Objects'][1]['name'] // BBB
Related
Hi i am quite new in Android client php server. I follow some tutorial for post and response variable by JSON but this reponse error. Value of type java.lang.String cannot be converted to JSONObject.
The JSON post is success but the response is error.
Android code:
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://192.168.1.1/databastest/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
resultLoging = jsonObject.getString("ResultArray");
}catch (Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return true;
}
#Override
protected void onPostExecute(Boolean valid){
//Update the UI
Toast.makeText(mContext, resultLoging, Toast.LENGTH_LONG).show();
if(exception != null){
Log.i("Error",exception.getMessage());
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
php code
mysqli_query($con,"INSERT INTO usersacc
(phone, password) VALUES('$pho', '$pass')");
#Build the result array (Assign keys to the values)
$result_data = array(
'ResultArray' => 'success',
);
#Output the JSON data
echo json_encode($result_data);
The insert is successful but the result not done.
Replace this your code with this may work.Get the response from server as Object not as String.
Object result = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(result.toString());
resultLoging = jsonObject.getString("ResultArray");
I am having problem in getting one dimensional JSON please guide me where either the problem is in my JSON or in my code?
JSON:
{
"data": {
"id": "S000010",
"name": "ZS Solutions",
"email": "zswebs#gmail.com",
"phone": "051-1234567",
"address": "p.o.box 123",
"about": "im the company\r\nHAhahhaa"
}
}
Android activity JSON retrieval code:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// TODO Auto-generated method stub
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("abc.php?Id="+id+"");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse hresponse = httpclient.execute(httppost);
HttpEntity entity = hresponse.getEntity();
is = entity.getContent();
String result=co(is);
JSONObject json=new JSONObject(result);
JSONArray a= json.getJSONArray(data);
for (int i = 0; i <= a.length(); i++) {
json = a.getJSONObject(i);
String cname=json.getString("name");
String cemail=json.getString("email");
String cphone=json.getString("phone");
String caddress=json.getString("address");
String cabout=json.getString("about");
Log.w("DATA ","NAME "+cname+"E-mail "+cemail+"Phone "+cphone+"ADDRESS"+caddress+"ABOUT"+cabout);
}
}
catch(Exception e){}
JSONArray a= json.getJSONArray(data); <-- this causing the Exception as
data is not a json Array, instead , it is a JSONObject
Your code should be
JSONObject json=new JSONObject(result);
JSONObject jsonobj=json.getJSONObject("data");
String cname=jsonobj.getString("name");
String cemail=jsonobj.getString("email");
String cphone=jsonobj.getString("phone");
String caddress=jsonobj.getString("address");
String cabout=jsonobj.getString("about");
How to call the php through javascript in apk , i am using webwiew and html5 javascript and jquery
I want to retrieve the json data from php
function ajaxFunction() {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.addRequestInterceptor(new RequestAcceptEncoding());
httpclient.addResponseInterceptor(new ResponseContentEncoding());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.smartcloudinfo.com/game/RainbowTreasure(IPAD)/RT_IPADV1.0.40/json.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("line_value",20));
nameValuePairs.add(new BasicNameValuePair("stake_value",0.2));
nameValuePairs.add(new BasicNameValuePair("balance_value",updated_Balance));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
alert("found"+HttpResponse response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
You need to use ajax. Jquery has a built in functionality to make ajax calls. Especially if you want to post your answer in json, there is also a call in jquery to do such things.
Here is a simple sample from the jquery page:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});
Or for JSON:
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
alert("JSON Data: " + json.users[3].name);
});
Seems Android app sends the JSON Object without problems but when i receive i get a :
"Notice: undefined index"
The Code that sends the Object is here :
public void sendJson( String name1, String name2 ) throws JSONException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/JSON_FOLDER/JSON2/parseData.php");
HttpResponse response;
JSONObject json = new JSONObject();
try {
json.put("name1", name1);
json.put("name2", name2);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.getParams().setParameter("json", json); // new code
//Execute HTTP POST request
httppost.setEntity(se);
response = httpclient.execute(httppost);
if( response != null ) {
str = inputStreamToString(response.getEntity().getContent()).toString();
Log.i("DATA", "Data send== " + str );
}
} catch ( ClientProtocolException e ) {
e.printStackTrace();
} catch ( IOException e ) {
e.printStackTrace();
}
}
On the Server side :
$json = $_POST['name1'];
$decoded = json_decode($json, TRUE);
and i got the undefined index notice.
Edit - revising my answer:
It appears you are sending a single parameter called json that contains 'name1' and 'name2' as the data.
Something like this should work: On the PHP side you need to decode the JSON first:
$json = json_decode($_POST['json']);
then you can access name1 and name2:
$name1 = $json['name1'];
$name2 = $json['name2'];
If you still get errors, I suggest printing out the $_POST and $_GET objects and see how your data is being sent. Then you will know how to access it.
Update:
the result you're getting array(0) { } means PHP did not get any parameters (GET or POST) from your request. You might try a different android example like this one:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://example.com/JSON_FOLDER/JSON2/parseData.php");
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject json = new JSONObject();
json.put("name1", name1);
json.put("name2", name2);
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
if( response != null ) {
str = inputStreamToString(response.getEntity().getContent()).toString();
Log.i("DATA", "Data send== " + str );
}
Reference Article
i want to send data from android application to local server (PHP) but it doesn't work
this is my code (it is work with remote server ):
String path ="http://localhost/sd.php";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(path);
json.put("im", 999);
json.put("cTime", 12);
Log.i("jason Object", json.toString());
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
} catch (Exception e) {
Object n=e.getStackTrace();
Toast.makeText( getApplicationContext(),n.toString(),Toast.LENGTH_SHORT).show();
}
i thing the wrong in the address http://localhost/sd.php
pleas help me to find a solution to this problem
You need the IP address of the server. Localhost from the app is the phone.