I am developing a software wherein I send a post request to server (which is written in PHP) but the server receives null value. Any help would be appreciated.
Android and PHP files enclosed.
**This is my Android file:**
public static JSONObject tosend = new JSONObject();
for(int i=0;i<3;i++)
{
JSONObject jo = new JSONObject();
jo.put("infoName", infoName[i]);
jo.put("infoNumber", infoNumber[i]);
jo.put("direction",direction[i]);
jo.put("version",version[i]);
JSONArray ja = new JSONArray();
ja.put(jo);
tosend .accumulate("introduceesJson", ja);
}
String link = "http://172.65.45.7/checkAppInstalled.php";
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(link);
StringEntity se;
se = new StringEntity(tosend.toString());
// Set HTTP parameters
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "*/*");
httpPostRequest.setHeader("Content-type", "*/*");
//httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
//long t = System.currentTimeMillis();
/* HttpPost httpPostRequest = new HttpPost(link);
List<NameValuePair> nVP = new ArrayList<NameValuePair>(2);
nVP.add(new BasicNameValuePair("json", tosend.toString()));
httpPostRequest.setEntity(new UrlEncodedFormEntity(nVP));*/
//Log.e("Posted data", "TestPOST - nVP = "+nVP.toString());
// Hand the NVP to the POST
Log.e("posted data",tosend.toString());
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
if (response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
String jsonReceived = EntityUtils.toString(entity);
Log.e("result received",jsonReceived);
}
Here's my PHP code:
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
if(!empty($jsonObj)) {
foreach($jsonObj as $json){
echo $json['infoName'];
echo $json['infoNumber'];
echo $json['direction'];
echo $json['version'];
}
}
else
{
echo "json empty";
}
Here is the logcat result:
04-02 15:34:07.882 9526-9704/com.thoughtrix.introduce E/posted data﹕ {"introduceesJson":[{"infoName":"Aa","direction":"2","version":"1","infoNumber":"96 35 874125"},[{"infoName":"Aa","direction":"2","version":"1","infoNumber":"96 35 874125"}]]}
Result Received : json empty.
Dont know much from json but fiddled around a bit: Try this:
var_dump($jsonObj['introduceesJson']);
$jsonArray = $jsonObj['introduceesJson'];
foreach($jsonArray as $json)
{
echo("------\n");
var_dump ($json);
foreach ( $json as $jsonarray )
{
echo(" ------\n");
var_dump ($jsonarray);
echo $jsonarray['infoName'];
echo $jsonarray['infoNumber'];
echo $jsonarray['direction'];
echo $jsonarray['version'];
echo ("\n");
}
} –
Could you please post the complete php script to extract all variables when you are done? I was puzzled...
Related
I am sending a Json array to server :
{
"Name":"Number",
"Name":"Number"
, ...
}
How can i receive it on PHP ?
Send method is POST .
Here is my android code :
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.1.7/admina/contacts_inout.php");
String json = "";
json = jsons.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
Since PHP only handles POST-data which is application/x-www-form-urlencoded or multipart/form-data formatted, you'll have to use the RAW input
use
$sent_array = json_decode(file_get_contents('php://input'),true);
to get the data as an array
isset($_POST['your_param_key']) or exit('param not found.');
$json = $_POST['your_param_key'];
$array = json_decode($json, true);
print_r($array);
I am a beginner in android development. I want to connect a php file to the android app. My php code is
<?php
$con = mysqli_connect("localhost", "root", "", "invoice_db");
if(mysqli_connect_errno($con)) {
echo "Failed to connect";
}
$response["sucess"]=0;
$invoiceid = $_POST['invc'];
$response = array();
$sql = "SELECT sl_no from invoice_table where invoice_id='$invoiceid'";
$result = mysqli_query($con,$sql);
if(!empty($result)) {
$row = mysqli_fetch_array($result);
$data = $row[0];
$response["sucess"] = 1;
}
mysqli_close($con);
?>
Here 'invc' is get from httpRequest ,
JSONObject json = jsonParser.makeHttpRequest(url_check_user, "POST", params);
And my JSONParser page contains,
if (method == "POST") {
// request method is POST
// defaultHttpClient
System.out.println("Inside json parser POST condition");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
System.out.println("Inside json parser POST condition" + params);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("From httpentity", httpEntity.toString());
System.out.println("ppppppppppppphhhhhhhhhhhhhhhhhhhhppppppppppp");
is = httpEntity.getContent();
}
Now I want to check , whether the parameters were passed to the php page or not. So I want to console/log cat the $invoiceid. How can it possible in Eclipse Ide?
If you want to print a variable inside PHP code, you can do echo $variable. However please note that PHP code will be executed on a server and not on your android device. Moreover your PHP code is vulnerable to sql injection attacks
You can use JSON encoding method in your php file to get a proper JSON response like this.
$response = array (
'invoiceid' => $verify_code,
);
print json_encode($response);
which will return a JSON string to your app in a format like
{"invoiceid":"null"}
which you can decode and log it like this
InputStreamReader isw = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isw);
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = br.readLine()) != null){
buffer.append(line);
}
String finalresult = buffer.toString();
JSONObject myobject = new JSONObject(finalresult);
String flag= myobject.getString("invoiceid");
log.e("mylog",flag)
so that it will be visible in your logcat file.
I got a problem. I read a lot here but unfortunately I can't get an answer for my problem.
I want to send a Json post to my Server. The Server should then save the string in my database.
This is my server code so far:
<?php
include('db_connect.php');
$db = new _DB_Connect();
$db->connect();
if(isset($_POST['regid'])){
$data = json_decode($_POST['regid']);
$save_entry = "insert into gcm_users (gcm_regid) values ('$data')";
mysql_query($save_entry) or die (mysql_error());
}else{
echo 'no data get';
}
?>
And this is my method on my android phone.
public String sendJson(View view){
InputStream inputStream = null;
String result = "";
String url2 = "http://192.168.0.5/control_center/functions/incomming.php";
TextView textView_result;
textView_result = (TextView) findViewById(R.id.textView_result);
//strict mode for networking
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url2);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type" , "application/json");
JSONObject jsonObject = new JSONObject();
jsonObject.put("regid", "blablabla");
String json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
HttpResponse httpResponse = httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null) {
System.out.println(convertInputStreamToString(inputStream));
}
else {
result = "Did not work!";
}
textView_result.setText(httpResponse.toString());
System.out.println(jsonObject.toString());
}catch(JSONException e){
e.printStackTrace();
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
Now the
System.out.println(convertInputStreamToString(inputStream));
tells me that I got no data
echo 'no data get';
So I get a response form the server but I could find my error, why the post data could not be retrieved.
Would appreciate any help or hints. Thank you.
try this...
JSONObject jsonObject = new JSONObject();
jsonObject.put("regid", "blablabla");
String json = jsonObject.toString();
MultipartEntityBuilder multiPart = MultipartEntityBuilder.create();
multiPart.addTextBody("regid",json);
or
multiPart.addTextBody("regid","blablabla");
httpPost.setEntity(multiPart.build());
I would like to send a value to the end of a url.
ex:
if I have id=1;, I want to send this id to end of my url (to obtain id) :
www.example.com/get/id
id values are different. (ex:id=2;id=3;id=4...).
is it possible ? how can I use HttpPost for this Scenario ?
I am using these functions but I always get this message :
no parametrs was sended !
inside my url :
www.example.com/get/id :
function get($id=0){
$id = (int)$id;
if(!$id) exit("no parametrs was sended !");
$trac = $this->m_general->get('tractions' , array('id' => $id ) , true );
if(!$trac ) $resp = "-1";
else
if($trac->expired != 0 || $trac->cradit_end_date < date('Y-m-d'))
{
$resp = 0;
}else
$resp = 1;
echo json_encode(array('response'=>$resp));
}
function set(){
$data = $this->input->post('data');
if(!$data) exit("no parametrs was sended !");
$message = $data;
$message = substr($message,7,-6);
list($qr,$date,$time) = explode("&",$message);
$insert = array(
'qr'=>$qr ,
'date'=>$date ,
'time'=>$time ,
'main'=>$message
);
$this->m_general->add('qr' , $insert );
}
private void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.url_server_side);
HttpResponse response = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
String res = EntityUtils.toString(response.getEntity());
Log.e("Response = ", res);
isok = 1 ;
} catch (ClientProtocolException e) {
e.printStackTrace();
// TODO Auto-generated catch block
isok = -1 ;
} catch (IOException e) {
e.printStackTrace();
// TODO Auto-generated catch block
isok = -1 ;
}
//Log.e("res", response.toString()) ;
}
As you mentioned above your web application expecting GET method to pass variables. In java code you are sending a POST request. You should use GET method to pass data.
String url = "http://www.example.com/id/YOUR_ID_DATA/data/YOUR_DATA";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
Or send both id, data in a POST request and accept as a POST response from PHP side.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com");
HttpResponse response = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", YOUR_ID_DATA));
nameValuePairs.add(new BasicNameValuePair("data", YOUR_DATA));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Then in PHP Side
$id = $_POST["id"];
$data = $_POST["data"];
I am new to php. I am posting data to php server from android as--
JSONObject jsonObject = new JSONObject();
try
{
jsonObject.put("name", "john");
String url = "http://10.0.2.2/WebService/submitname.php";
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("json", jsonObject.toString());
StringEntity se = null;
se = new StringEntity(jsonObject.toString());
se.setContentEncoding(new BasicHeader(
HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
int i = response.getStatusLine().getStatusCode();
Log.v("status", "" + i);
} catch (Exception e)
{
e.printStackTrace();
}
And receiving the data in php as
<?php
mysql_connect("localhost","root","");
mysql_select_db("my db");
$var = json_decode($_POST['HTTP_JSON']);
$service = $var->{'name'};
mysql_query("INSERT INTO name_table(`_id`, `retrived_name`, `cat`, `is_valid_name`) VALUES (1547, '$service','$var',true);");
echo $var;
?>
Getting nothing on server side. However php query is executing correct as getting 200 response and a new row in database but with empty retrived_name and cat field.
How do I solve this? Thanks in advance!
You Should provide the values in Query:
<?php
mysql_connect("localhost","root","");
mysql_select_db("my db");
$var = json_decode($_POST['HTTP_JSON']);
$service = $var->{'name'};
$name = $_POST['name'];
mysql_query("INSERT INTO name_table(`_id`, `retrived_name`, `cat`, `is_valid_name`) VALUES (1547, '$service','$name',true);");
echo $var;
?>