android How to send POST json request to Laravel Framework - php

Hi im doing both android and laravel framework..
but when i do post method and send json to laravel api via POST.. it will give a 500 result.. please help..
this is one of my asynctask in android sending the post data.. assume sendJsonObj is a jsonobject with values..
URL url = new URL("http://dexter-laravelframe.rhcloud.com/register");
urlConnect = (HttpURLConnection) url.openConnection();
urlConnect.setRequestMethod("POST");
urlConnect.setConnectTimeout(10000);
urlConnect.setRequestProperty("Content-Type", "application/json");
urlConnect.setRequestProperty("x-csrf-token", Model_Application.token_csrf);
urlConnect.connect();
OutputStreamWriter outWrite = new OutputStreamWriter(urlConnect.getOutputStream());
outWrite.write(sendJsonObj.toString());
outWrite.flush();
outWrite.close();
int code = urlConnect.getResponseCode();`
on my Laravel framework..
routes.php
Route::post('/register', 'UserController#register');
UserController.php
public function register()
{
$json = Input::json()->all();
$resultJson = json_encode($json);
echo $resultJson;
}
this will give a 500 response code from Laravel api.. i want it to read the json data.. and send it back.. if i used Mozilla plugin rest client, and send the json data in body.. it gives 200..

Related

OkHttp POST Does Not Seem to Send Request Body

I am trying to use RetroFit2 and OkHttp3 to do a POST method on a PHP script. I have been doing GET methods perfectly fine, but I have been having problems with posting.
I have an HttpLoggingInterceptor set up with my OkHttpClient, and it logs the request body perfectly. But my PHP script was not receiving the data, so I tried just outputting the $_POST data as soon as I got it, but it is an empty string. I cannot tell if there is something wrong on the Android side, the server side, or both.
My RetroFit object and OkHttpClient are set up like so:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.cookieJar(RestCookieJar.getInstance())
.addInterceptor(interceptor)
.build();
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(Instant.class, new InstantAdapter())
.registerTypeAdapter(LatLng.class, new LatLngAdapter())
.registerTypeAdapter(Uri.class, new UriAdapter())
.create();
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.baseUrl(BASE_URL)
.build();
RestService service = retrofit.create(RestService.class);
Then my RestService interface is set up like this:
public interface RestService {
#GET("api/index.php")
Call<List<Session>> getSessions();
#POST("api/index.php")
Call<ResponseBody> postSession(#Body Session session);
}
As I mentioned, this all seems to work, but when I call:
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
print_r($_POST);
}
I get an empty set of parenthesis.
I found my answer here: php $_POST array empty upon form submission. Retrofit automatically sets the Content-Type to "application/json; charset=UTF-8", which in PHP versions 5.0 - 5.19, there is a bug causing the request body to not be parsed into the $_POST variable. The server I am using is running PHP 5.10 (which I have no control over).
The workaround for this bug is to parse the JSON data yourself from the raw request body:
if($_SERVER['CONTENT_TYPE'] === 'application/json; charset=UTF-8') {
$_POST = json_decode(file_get_contents('php://input'));
}

Talking to PHP get commands from Android app

I have an android app and am trying to send data to the PHP on the server. The server gets the php data with
$this->get('uname');
$this->get('pass');
We do use codeigniter if that matters
The Java code, inside of an Async method, I currently have is
InputStream response = null;
URLConnection connection = new URL(urls[0]).openConnection();
connection.setRequestProperty("uname" , Username);
connection.setRequestProperty("pass", Password);
response = connection.getInputStream();
When I run this, the code always returns null but it is supposed to return a JSON array either way. I have checked the URL and it is correct. What am I doing wrong? Thanks!
You code should be like this
For your android side ,as mentioned by #Ichigo Kurosaki at Sending POST data in Android
For Codeigniter side , cosider you function name is user_login
function user_login(){
$uname = $this->input->get_post('uname'); //get_post will work for both type of GET/POST request
$pass = $this->input->get_post('pass');
$result=$this->authenticate->actLogin($uname,$pass ); //considering your authenticating user and returning 1,0 array as success/failure
$this->output
->set_content_type('application/json')
->set_output(json_encode($result));
exit;
}

How to insert data on to the server in Android Application

I am developing an android application where the user data should be pushed onto the server .How can i do that ? I was able to get data from the server but unable to insert it. Code snippet would be good.I have tried this but it doesn't work.
Java Code :
String data="xyz.org/json.php"+"?"+"&"+URLEncoder.encode("data", "UTF-8") + "="+"order";
URL url;
url = new URL(data);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
In json.php :
$data = urldecode($_GET['data']);
if($data=="order")
{
$query="insert into xyz values('$x','$y','$z')";
$query_run=mysql_query($query);
}
you need a httppost or httpget dependance on the your url method for that you can use Httppost and get follow this url you get some idea and also check this url for asynctask beacuse you have to put all the network related you have to put in the asynctask.

Calling ASP.NET Web Api method with PHP

I have the following web method in my web api controller
public HttpResponseMessage PostMakeBooking(FacilityBookingRequest bookingRequest)
{
var returnStatus = HttpStatusCode.OK;
var json = new JavaScriptSerializer().Serialize(bookingRequest);
var response = Request.CreateResponse<CardholderResponse>(returnStatus, cardholderResponse);
return response;
}
When I make this call from my .NET app, my json string appears correctly when I seralize it
{"correlationId":null,"RequestId":"7ec5092a-342a-4e32-9311-10e7df3e3683","BookingId":"BK-123102","CardholderId":"123456","BookingFrom":"\/Date(1370512706448)\/","BookingUntil":"\/Date(1370523506449)\/","DeviceId":"ACU-01-R2","Action":"Add","LoginId":"tester","Password":"tester"}
However, when I made to call from my php script
public function web_request(){
$guid =self::getGUID();
$replace = array("{","}");
$guid = str_replace($replace, "", $guid);
$client = new Zend_Rest_Client("http://203.92.72.221");
$request= new myZendCommon_FacilityBookingRequest();
$request->RequestId =$guid;
$request->BookingFrom ="27/03/2013 05:30";
$request->BookingUntil ="27/03/2013 06:30";
$request->CardholderId ="E0185963";
$request->DeviceId ="ACU-B2-01-R1";
$request->BookingId ="111";
$request->Action ="Add";
$request->LoginId ="tester";
$request->correlationId ="(null)";
$request->Password ="tester";
$request = json_encode($request);
$response = $client->restPost("/ibsswebapi/api/facilitybooking",$request);
print_r($response);
exit();
The call goes to my web method, but when I serialize it using JavaScriptSerializer().Serialize(bookingRequest)
{"correlationId":null,"RequestId":null,"BookingId":null,"CardholderId":null,"BookingFrom":"\/Date(-62135596800000)\/","BookingUntil":"\/Date(-62135596800000)\/","DeviceId":null,"Action":null,"LoginId":null,"Password":null}
All the values are null.
Is something wrong with the script?
I believe Kiran is right. Not sure why some one has felt his answer is not useful. Anyways, my understanding is that you are creating a JSON string and doing a form post of the same. I guess in this case the content type is sent as application/www-form-urlencoded but request body is a JSON string. You can use Fiddler to see how the request is being sent by the PHP script. I don't have the PHP knowledge to tell you how you can post JSON but my guess is that if you just remove the JSON encoding line $request = json_encode($request);, it should be okay.
From ASP.NET Web API point of view, if the request has Content-Type: application/json header and the body has the right JSON or if the request has Content-Type:application/www-form-urlencoded header and the body has the form url encoded content like RequestId=7ec5092a-342a-4e32-9311-10e7df3e3683&BookingId=BK-123102 and so on, web API will absolutely have no problem in binding. Currently, the request is not being sent in the right format for web API to bind.
Are you sending the header Content-Type:application/json in your request?
Also add the following piece of code to catch any model state validation errors:
.
if (!ModelState.IsValid)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState));
}

Handling JSON POST request in PHP

I am currently developing Android application, which will uses web services. I used PHP for backend. I am currently trying authentication via JSON to PHP. But I am stuck at some point, hope u guys will help.
I successfully write code to create JSON data in android also db connections in php using mysql, but i am confusing about how to handle JSON data. I am using POST request for sending JSON data.
I like to ask how i handle JSON data in PHP. More specific, I like to know how to grab POST request in PHP which contain JSON data??
Thanks in advance.
Thanking you.
EDIT:
I am using following code for sending POST request in android
HttpPost post = new HttpPost(address);
json.put("username", username);
json.put("password", pwd);
StringEntity se = new StringEntity("json"+json.toString());
Log.i(DEB_TAG, "The JSON Request is:"+json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
Log.i(DEB_TAG, "The post request is "+post.toString());
response = client.execute(post);
if(response != null){
InputStream in = response.getEntity().getContent();
Log.i(DEB_TAG, "The result is"+in.toString());
}
and using following code for parsing JSON request in php:
$string = $_POST['josnHeader'];
$obj = json_decode($string);
$username = $obj->{'username'};
$password = $obj->{'password'};
Is it correct or I am doing any wrong implementation??
Have you taken a look in your $_POST array in PHP?
$json = $_POST["var_name"];
$array = json_decode($json);
$json = $_REQUEST["your_param"];
$dtoObject = json_decode(stripslashes($json),true);

Categories