I am developing an android application that uses the PHP/MySQL to send data from app to server in order to register/login users. I already wrote the Javascript and PHP files to send and receive JSON data an insert it into MySQL database. The problem I have is how to handle different responses from PHP.
Exemple:
<?php
//decode json object
$json = file_get_contents('php://input');
$obj = json_decode($json);
//variables
$user_firstname = $obj->{'user_firstname'};
$user_lastname = $obj->{'user_lastname'};
$user_email = $obj->{'user_email'};
$user_password = $obj->{'user_password'};
if([variables] != null){
//check for an existing email in db
mysql_query("Check if email exists");
if(email exist){
//pass a response to java file
return user_exists;
die();
}else{
//success
return success;
}
}
?>
All I want is to handle those different return values in order to interact with the user inside the android app.
I think you should user HTTP response codes for this. For example, your php script will return HTTP 200 - OK when user successfully created and HTTP 409 Conflict when user already exists. This is how RESTfull APIs usually works this. On Android you'll have to check the status code and decide what to do.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpget = new HttpPost("http://www.google.com/");
HttpResponse response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
You can craft a json response by creating an associative array and passing it to json_encode() which will return a string that you can echo to the java client. Don't forget to set the appropriate Content-Type header using the header() function. It's also a good idea to set the HTTP response code appropriately. I'm picturing something like this:
$responseArray = array('response' => 'success'); // or 'user_exists'
$responseJson = json_encode($responseArray);
header('HTTP/1.1 200 OK'); // or 4xx FAIL_TEXT on failure
header('Content-Type: application/json');
echo $responseJson;
You'll then have to parse this response on the java client.
Related
Im calling a vehicle data API at an endpoint and can return the data fine using:
$client = new Client();
$url = "https://uk1.ukvehicledata.co.uk/api/MISC DETAILS;
$result = $client->get($url);
return $result->request;
This is using mock data so the response is:
{
"Request":{
"RequestGuid":"",
"PackageId":""
"Response":{
// VEHICLE DATA
}
}
However, I now wish to store the response in the database but cannot access ->request or ->Request etc.
Using:
return json_encode( (array)$result );
Actually returns the headers from Guzzle and no response data.
Any help?
You have to convert the body into JSON first:
$jsonArray = json_decode($result->getBody()->getContents(), true);
echo $jsonArray['Request']['RequestGuid'];
I'm trying to use OKHttp to send a request to my php backend. I'm using this code:
public static String putRequestWithHeaderAndBody(String url, String header, String jsonBody) throws IOException
{
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonBody);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.put(body) //PUT
.addHeader("Authorization", header)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
I then try to read the put body from php using this line of code:
$data = json_decode(file_get_contents("php://input"), true);
However, it always seems to be empty. I feel like I am making a silly mistake, I cannot seem to find out what is wrong though.
The request does return the correct response body when I send it using Postman.
I have REST api on backend created with php (slim php micro framework). So code is:
INDEX.php
$app->post('/coords', 'authenticate', function() use ($app) {
$response = array();
//$jsonData = $app->request->post('podaci');
$jsonData = #file_get_contents('php://input');
$aData = json_decode($jsonData);
$latitude = $aData->location->latitude;
$longitude = $aData->location->longitude;
$podaci = $latitude.' ddd '.$longitude;
global $user_id;
$db = new DbHandler();
// creating new task
$coords_id = $db->createCoords($user_id, $podaci);
if ($coords_id != NULL) {
$response["error"] = false;
$response["message"] = "Coords insert successfully";
echoRespnse(201, $response);
} else {
$response["error"] = true;
$response["message"] = "Coords not inserted";
echoRespnse(200, $response);
}
});
I also have DBhandler file , code (function createCoords):
public function createCoords($user_id, $podaci) {
$stmt = $this->conn->prepare("INSERT INTO coords(podaci) VALUES(?)");
$stmt->bind_param("s", $podaci);
$result = $stmt->execute();
$stmt->close();
}
I try this REST api with sample data with ajax request and work well, but now I need to POST data from phonegap app to server and I write:
// BackgroundGeoLocation is highly configurable.
bgGeo.configure(callbackFn, failureFn, {
url: 'http://agroagro.com/agroMobile/v1/coords', // <-- Android ONLY: your server url to send locations to
params: {
Auth: 'df6017abde2d2re560896b63a0ee1039', // <-- Android ONLY: HTTP POST params sent to your server when persisting locations.
foo: 'bar' // <-- Android ONLY: HTTP POST params sent to your server when persisting locations.
},
desiredAccuracy: 0,
stationaryRadius: 50,
distanceFilter: 50,
notificationTitle: 'Background tracking', // <-- android only, customize the title of the notification
notificationText: 'ENABLED', // <-- android only, customize the text of the notification
activityType: 'AutomotiveNavigation',
debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
stopOnTerminate: false // <-- enable this to clear background location settings when the app terminates
});
I read here how to make php file to get INPUT data: https://github.com/christocracy/cordova-plugin-background-geolocation/issues/79
as you can see from my index.php code I write everything fine but what can be problem? This just dont work when I test on my android phone.
I do not why you are using 'php://input'); for getting json data.
Its simple. use the following to grab the json data sent from your phone.
$request = $app->request();
$body = $request->getBody();
$input = json_decode($body);
To know more how to handle json data using slim you may try the following website.
http://www.ibm.com/developerworks/library/x-slim-rest/
I asked a similar question earlier, in a nutshell I have an API application that takes json requests and outputs an json response.
For instance here is one of the requests that I need to test out, how can I use this json object with my testing to emulate a 'real request'
{
"request" : {
"model" : {
"code" : "PR92DK1Z"
}
}
The response is straightforward (this bit has been done).
From other users on here this is the optimised method using Yii to do this, I am just unsure how to emulate the json request - e.g essentially send a JSON HTTP request, can anyone assist on how to do this?
public function actionMyRequest() {
// somehow add my json request...
$requestBody = Yii::app()->request->getRawBody();
$parsedRequest = CJSON::decode($requestBody);
$code = $parsedRequest["request"]["model"]["code"];
}
I don't understand if you want your app to send an http request and get the result or at the opposite receive a http request
I answered for the first assumption, I'll change my answer if you want the other
For me the best way to send an HTTP request is to use Guzzle http client.
This is not a yii extension, but you can use third party libraries with yii.
Here's an example from Guzzle page:
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode(); // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody();
So in your case you could do something like:
public function actionMyRequest() {
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.your-url.com/');
$requestBody = $res->getBody();
$parsedRequest = CJSON::decode($requestBody);
$code = $parsedRequest["request"]["model"]["code"];
}
I had completed a small Android project(MAP and Location based) 4 months before. Now I am planning to improve the App by upgrading the map API and some code tweaking. As a part of this, I would like to ask that how can I check the response for an HTTP request from the web-server efficiently. My current strategy is:
App will upload the data to PHP server by using HTTP GET method.
The response from server will be in the form of XML tagged format.
I must have to check the corresponding tag for the response from server(use xmlParser example seen in Stack Overflow xml parser).
I think this is little bit annoying for me. Is there any easy method to achieve this process?
Example:
If the user tries to log-in, the credential will be checked in SERVER and successful authentication will be replied as some code: 1 else: 0.
All the HTTP requests are handled as asynctask.
public String login(String login_url,List<NameValuePair> login_parameters_list) throws ClientProtocolException, IOException
{
int response_code = -1;
HttpPost httppost = new HttpPost(post_url);
httppost.setEntity(new UrlEncodedFormEntity(post_parameters_list));
HttpResponse response = httpclient.execute(httppost);
// coockie management
httpclient.getCookieStore().getCookies().get(0).getName();
response_code = response.getStatusLine().getStatusCode();
if(response_code == 999 || response_code == HttpStatus.SC_INTERNAL_SERVER_ERROR)
{
Log.e("HttpResponse", "Internal Server");
}
else if(response_code == -1 )
{
Log.e("HttpResponse", "Socket connection timeout");
}
if (response_code == HttpStatus.SC_UNAUTHORIZED)
{
// credential check failed
Log.e("HTTP status", "unauthorised");
}
else if (response_code == HttpStatus.SC_FORBIDDEN)
{
// forbidden
Log.e("HTTP status", "Forbidden");
}
return response_code == HttpStatus.SC_OK ? EntityUtils.toString(response.getEntity()) : null;
}