How to get the JSON Object in PHP from Android OKHttp - php

I have my OkHttp code here (i'm working in Android)
void postRequest(String postUrl, String postBody) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON,postBody);
Request request = new Request.Builder()
.url(postUrl)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("TAG",response.body().string());
}
});
}
And this is my PHP part
<?php
header("Content-type: application/json; charset=utf-8");
include("conexion.php");
$nombre = $_POST["nombre"];
$apellidoPaterno = $_POST['apellidoPaterno'];
$apellidoMaterno = $_POST['apellidoMaterno'];
$direccion = $_POST['direccion'];
$redesSociales = $_POST['redesSociales'];
$telefono = $_POST['telefono'];
$nombreUsuario = $_POST['nombreUsuario'];
$contrasena = $_POST['contrasenaUsuario'];
?>
I want to obtain the values that are passing through my JSON, but when I use $_POST they end with no values. I've tried with the API of reqres and it does send the information.
Any help is appreciated, thanks.

Following your and my comments you could do the following:
<?php
// header("Content-type: application/json; charset=utf-8"); // not really needed here for now
include("conexion.php");
$fgc = file_get_contents("php://input");
$json = json_decode($fgc, true);
// now you've got all your values in $json:
$nombre = $json["nombre"];
alternatively you could do:
$json = json_decode($fgc);
// now you've got all your values as an object in $json:
$nombre = $json->nombre;
further reading: http://php.net/manual/de/wrappers.php.php#wrappers.php.input

try this:
//this only you use to issue a response in json format from your php to android
//header("Content-type: application/json; charset=utf-8");
include("conexion.php");
//The following lines serve to receive a json and transform them to the variables
$data = json_decode($_POST);
$nombre = $data->nombre;
$apellidoPaterno = $data->apellidoPaterno;
$apellidoMaterno = $data->apellidoMaterno;
$direccion = $data->direccion;
$redesSociales = $data->redesSociales;
$telefono = $data->telefono;
$nombreUsuario = $data->nombreUsuario;
$contrasena = $data->contrasenaUsuario;
Of course everything depends on how you are arming the body of the post sent, on the other hand if you are making a post request from android to your php, you do not need to convert the variables to json, just pass the body and already.
You must convert to JSON only the answers of your php towards android.
SAMPLE: https://ideone.com/x2ENdd

Related

Cannot acces post data sent from okhttp from php

i send post request with a json object to php in server, but php keep telling $_POST is empty.
this is okhttp code
public String postConection(JSONObject pJson, String pUrl) throws IOException {
final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String dirArchivo = "http://10.0.2.2/SoulStoreProject/"+pUrl;
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, pJson.toString());
Request request = new Request.Builder()
.url(dirArchivo)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
and this is the php code
$nick = $_POST['nick'];
$password = $_POST['password'];
$query = "
INSERT INTO
players(nick, password)
VALUES($nick,$password)
";
$DB->Execute($query);
You are posting in JSON format so you need to grab the post with file_get_contents('php://input') and then decode it so that you have it as an array.
$_POST only works with posts that are encoded with enctype=”multipart/form-data”
$post = json_decode(file_get_contents('php://input'),true);
$nick = $post['nick'];
$password = $post['password'];
$query = "INSERT INTO players(nick, password) VALUES(?,?)";
$sth = $DB->prepare($query);
$sth->Execute(array($nick, $password));

Unknown JSON error on my PHP server

I'm working on an application that allows data transfer from Android to PHP server and I don't know why it doesn't support JSON?
Here is my code:
<?php
JSON.parse();
$decode = json_decode($_REQUEST['request']);
$json = $decode->name;
header('Content-type:application/json');
echo json_encode($json);
?>
check your JSON at http://jsonlint.com
If the JSON is valid than your php code may not be correct.
Show some code for specifics.
You can send Json data as string from android using following code :
BufferedReader reader = null;
// Send data
try {
/* forming th java.net.URL object */
URL url = new URL(this.url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
/* pass post data */
byte[] outputBytes = jsonData.toString().getBytes("UTF-8");
OutputStream os = urlConnection.getOutputStream();
os.write(outputBytes);
os.close();
/* Get Response and execute WebService request*/
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == HttpsURLConnection.HTTP_OK) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
ResponseData= convertStreamToString(inputStream);
} else {
ResponseData = null;
}
and in php,you can get data by adding following code :
$post_body = file_get_contents('php://input');
$post_body = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($post_body));
$reqData[] = json_decode($post_body);
$postData = $reqData[0];
echo $postData->name;

How to post data of 'content-type application/json' to slim php rest service

i am having issue for posting data of mime type content-type application/json from Chrome Advance rest Client to slim framework web service.
I tried these codes to send in application/json
$app->post('/register', function() use ($app) {
$app->add(new \Slim\Middleware\ContentTypes());
$params = $app->request->getBody();
$name = $params->name;
$email = $params->email;
$password = $params->password;
...});
tried this also
$params = json_decode($app->request()->getBody());
var_dumb($params); //get NULL value here
Getting errors of
Trying to get property of non-object to this `$name = $params->name;`
Please help me how to catch application/json format of data?
Thank you
As per the above details, assuming your raw JSON looks something like this
{"name":"John Smith", "mail":"jhon#mail.com", "password":"foobar"}
You can access your params array like this
$app->post('/register', function () use ($app) {
$params = $app->request->getBody() ;
$params = array_filter($params);
if(!empty($params)){
$name = $params['name'];
$mail = $params['mail'];
$pass = $params['password'];
// print $name;
}
})->name("register");
or if you are posting in Advanced Rest client via Content-Type: application/x-www-form-urlencoded you can use $app->request->post(); to access your array
$app->post('/register/', function () use ($app) {
$userInfo = $app->request()->params() ;
//or
$userInfo = $app->request->post() ;
$name = $userInfo['name'];
$mail = $userInfo['email'];
$pass = $userInfo['password'];
// print $name
})->name("register");

calling json data to php at server side in android

Hi,
i use this class to make a request to server, which consist of the json data object.
Class is:-
public class HttpClient {
private static String URL = "localhost/json/json_handle.php";
public String postJsonData(String data) {
try {
StringBuffer buffer = new StringBuffer();
// Apache HTTP Reqeust
System.out.println("Sending data..");
System.out.println("Data: [" + data + "]");
org.apache.http.client.HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
List<NameValuePair> nvList = new ArrayList<NameValuePair>();
BasicNameValuePair bnvp = new BasicNameValuePair("json", data.toString());
// We can add more
nvList.add(bnvp);
post.setEntity(new UrlEncodedFormEntity(nvList));
HttpResponse resp = client.execute(post);
// We read the response
InputStream is = resp.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
is.close();
buffer.append(str.toString());
// Done!
return buffer.toString();
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
}
Then i use a php class on server side to get the json object from the request. But, at server side i am getting nothing. Even when i use $_REQUEST method, then code after this method doesn't work.
Here is my php file:-
<?php
$file = fopen("MyFile.txt" ,"w");
$int = $_REQUEST;
fwrite($file,"aaa");
//$input =$_REQUEST['json'];
fwrite($file,"HELLO 111");
//$data = json_decode($input,true);
/*print_r($input);
// get values
$firstname = $input->firstName;
$surename = $input->lastName;
$age = intval($input->age);
// check values
if (isset($firstname) && !empty($firstname) &&
isset($surename) && !empty($surename) &&
isset($age) && is_numeric($age))
{
// do something
echo "Hello ".htmlspecialchars($firstname)." ".htmlspecialchars($surename)."!<br>";
echo "You are $age years old! Wow.";
}
else
{
echo "Some values are missing or incorrect";
}*/
//fwrite($file, $data);
fclose($file);
?>
Any suggestions regarding this problem???
Thanks friends for your help.
I got the solution and now the program is working perfectly on localhost as well as online.
For localhost, we just have to give the URL as:-
1.1.1.1/json/json_handle.php
where 1.1.1.1 is your ip address.
Again, thanks alot friends.

Having trouble parsing Json with PHP

I have an android app that sends a json string to my server and it is formatted as follows:
{"drink_name":"testing","phone_number":"5555555555"}
When I use the command: SELECT * FROM orders, it shows that blank entries were inserted into the table.
I think my issue is arising from my PHP script (mainly because I am new to PHP).
Am I parsing the json correctly?
Below is the script that I wrote.
<?php
$handle = mysql_connect('localhost',USERNAME,PASSWORD);
if($handle==false)
{
die('No database connection');
}
$db=mysql_select_db('r2bar2');
$json = file_get_contents('php://input');
$obj = json_decode($json);
mysql_query("INSERT INTO orders (phone_number, drink_name)
VALUES ('".$obj->{'phone_number'}."', '".$obj->{'drink_name'}."')");
mysql_close($handle);
?>
EDIT:
Here is my Android code if it is any help.
protected void sendJson(final String phnNmbr, final String drink) {
Thread t = new Thread(){
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try{
HttpPost post = new HttpPost("http://kubie.dyndns-home.com/R2Bar2/sendOrder.php");
json.put("phone_number", phnNmbr);
json.put("drink_name", drink);
StringEntity se = new StringEntity( "orders: " + json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_LONG).show();
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
}
catch(Exception e){
e.printStackTrace();
//createDialog("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
I had used the same method except for how you are trying to access json data on the server.
I had used $_POST array to access it and it worked well for me. Try using,
$json = $_POST['orders'];
$obj = json_decode($json);
This had worked perfectly well for me. All the best :)
(I dont think there is a problem with $handle since something is being inserted into the table)
I figured out what I was doing wrong. It seems as though I was passing in a raw data type. In order to parse the string, I used the following:
$obj = json_decode(file_get_contents("php://input"));
mysql_query("INSERT INTO orders (phone_number, drink_name)
VALUES ('".$obj->{'phone_number'}."', '".$obj->{'drink_name'}."')");
Thanks everyone for your suggestions.
You have make a connection to the DB as follws,you have missed the $handle to make connection
$handle = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$handle) {
die('Not connected : ' . mysql_error());
}
// make r2bar2 the current db
$db=mysql_select_db('r2bar2',$handle);
if (!$db) {
die ('Can\'t use r2bar2 : ' . mysql_error());
}

Categories