Error sending parameters to php - php

when connecting android to php sometimes parameters not sent.
user=i.getExtras().getString("user");
params.add(new BasicNameValuePair("user",user));
// getting JSON string from URL
json = jParser.makeHttpRequest(url_orders, "GET", params);
result obtained based on empty user.

This worked for me try this :
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://URL.com.php");
postParameters.add(new BasicNameValuePair("param1", value1));
postParameters.add(new BasicNameValuePair("param2", value2));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString()

Related

Why is it my PHP Webservice cannot receive data from my Android device?

Both my laptop and my Android device is connected to the same WiFi. and I am trying to send data from my phone to the PHP webservice. But I can't get it work. What is the problem?
IP of my laptop: 192.168.0.10
IP of my phone: 192.168.0.9
I am listening from port80: ie:
HttpPost httppost = new HttpPost("http://192.168.0.10:80");
Following are the code of my PHP file:
<?php
$get = json_encode($_POST["req"]);
// Get data from object
$name = $get->req; // Get name you send
$age = $get->req; // Get age of user
?>
and below are my android code. Which part i'm doing wrongly? Please help!
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.10:80");
try {
JSONObject jsonobj = new JSONObject();
jsonobj.put("name", "Jensen");
jsonobj.put("age", "22");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("req", jsonobj.toString()));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
// Use UrlEncodedFormEntity to send in proper format which we need
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Another thing, I have tried sending the data over too. I will need to press a button then the data will be passed. After I press the button, this is what I got (I'm connecting my phone through ADB):

Posting variables with Android

I use my code to upload data in MySQL.
HttpPost httppost = new HttpPost(URL_POST_TIENDAS);
HttpClient client = new DefaultHttpClient();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", json));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
// Log.e(TAG, "Ejecutando POST: Mandando tiendas");
HttpResponse httpResponse = client.execute(httppost);
if (httpResponse != null) {
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
message = NetworkUtils.Entity2String(httpResponse);
Log.e(TAG, "Respuesta del Post Tienda:" + message);
}
} else {
Err error = new Err(statusCode, message, "upload_tiendas");
MyApplication.lErrors.add(error);
this.cancel(true);
}
This code give me a 500 Error
In PHP, I receive my variable with $_REQUEST, so when I debug my app, copy json variable and put it in the full URL, there is no problem.
This show my json variable is OK, as URL_POST_TIENDAS.
Why is there a problem with using POST??? This is not the first time I find this problem.
I always change it to GET, but this time, I want to understand why it fails, because I could have a lot of information to upload, so GET is not very appropriated!
EDIT : When seeing logs server, I don't see anything about my 500 error.
EDIT2: httpost :
httppost HttpPost (id=830032727152)
aborted false
abortLock ReentrantLock (id=830032727328)
connRequest null
entity UrlEncodedFormEntity (id=830032731528)
chunked false
content (id=830032746160)
[0...99]
[100...199]
[200...299]
[300...399]
[400...499]
[500...599]
[600...699]
[700...724]
contentEncoding null
contentType BasicHeader (id=830032747320)
headergroup HeaderGroup (id=830032727200)
headers ArrayList (id=830032727216)
array Object[16] (id=830032727240)
modCount 0
size 0
params BasicHttpParams (id=830032789608)
parameters null
releaseTrigger SingleClientConnManager$ConnAdapter (id=830032798576)
uri URI (id=830032727376)
Any Help will be appreciated !
Set content type in your httpPost
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
Update
Here is the blog which is doing the same thing.
Send data as json from android to a PHP server
You should use $_POST array instead of $_REQUEST when you are using POST method for sending params.
I think this will resolve your problem.

Receiving JSONObject in PHP

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

Android HTTPPost and HTTPResponse error

I'm working on an app and having this problem. I'm using PHP as back end server and JSON as data transfer technology. But problem is that, Http POST and RESPONSE are not working. Http GET is working and user is being logged in but no response is getting back and POST also not working.
Please help me if you understand the problem.
// Making HTTP request
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeOut); HttpConnectionParams.setSoTimeout(httpParameters, timeOut);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpEntity httpEntity = null;
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
}
try like this:
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
try {
URI url = new URI("xxxxxxxxxxxxxxxxxxxxxx");
HttpPost post = new HttpPost(url);
JSONObject json = new JSONObject();
json.put("x",x);
json.put("y", y);
StringEntity se = new StringEntity(holder.toString());
post.setEntity(se);
response = client.execute(post);
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
in.close();
}
} catch(Exception e) {
e.printStackTrace();
}

Why I can't getting json in android?

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

Categories