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));
}
Related
By using Symfony Panther, I sent a request and I wanted to get the response. I was able to get the body and the status code but for the header I just got an empty array.
$client = Client::createChromeClient();
$client->request('GET', 'https://google.com');
$client->getInternalResponse()->getHeaders(); // returned empty array!!!
Panther does not have access to the HTTP response as explained in this github issue https://github.com/symfony/panther/issues/17.
But if you read carefuly, you'll see that this is not a limitation of Panther but a limitation of Selenium WebDriver. See this post How to get HTTP Response Code using Selenium WebDriver.
This means that the answer to the question "Can I have access to the HTTP response code or the HTTP header using Symfony Panther?" is "No, it's not possible".
While this is not possible the workaround I found was to create an HttpClient and use it to make a request and get the response from it.
<?php
use Symfony\Component\HttpClient\HttpClient;
$client = HttpClient::create();
$response = $client->request('GET', $this->myBaseUri);
$statusCode = $response->getStatusCode();
$headers = $response->getHeaders();
Here's the documentation for HTTP Client (Symfony Docs) if you want to try this way.
According to this issue: https://github.com/symfony/panther/issues/67, it seems that status code is not managed ( HTTP 200 will always get returned, no matter what the request actually responded.)
And same for the headers, I'm afraid. If you look at class
Symfony\Component\Panther\Client and method get($url) you can see that:
$this->internalResponse = new Response($this->webDriver->getPageSource());
while Response's constructor accepts:
public function __construct(string $content = '', int $status = 200, array $headers = [])
Having these said, no matter what happens, you always get HTTP 200 and empty header array.
I am trying to send a PUT request method from my Android app to my PHP endpoint but in my endpoint the PUT request is not recognized as a PUT request so I return Request method is wrong! message from my endpoint.
Android interface and request execution
Interface for activation
#PUT("device/activate.php")
Call<DeviceRegistry> registryDevice();
Executing the request
DeviceRegistryAPI registryAPI =
RetrofitController.getRetrofit().create(DeviceRegistryAPI.class);
Call<DeviceRegistry> registryCallback = registryAPI.registryDevice();
response = registryCallback.execute();
With this I am expecting a response but I am getting my endpoint error message.
My PHP endpoint
if($_SERVER['REQUEST_METHOD'] == "PUT"){
//doing something with the data
} else {
$data = array("result" => 0, "message" => "Request method is wrong!");
}
I don't know why the $_SERVER['REQUEST_METHOD'] == "PUT" is false but I wonder if I am missing something on Retrofit 2.
More Info.
I am using Retrofit2.
Update 1: Sending json into the body
I am trying to send a json using the body.
It is my json:
{
"number": 1,
"infoList": [
{
"id": 1,
"info": "something"
},
{
"id": 2,
"info": "something"
}
]
}
There are my classes:
class DataInfo{
public int number;
public List<Info> infoList;
public DataInfo(int number, List<Info> list){
this.number = number;
this.infoList = list;
}
}
class Info{
public int id;
public String info;
}
I changed the PUT interface to this:
#PUT("device/activate.php")
Call<DeviceRegistry> registryDevice(#Body DataInfo info);
But I am getting the same problem.
Update 2: Do I need Header
I have this header in my REstfull client:
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Do I need to put this on my request configuration? How do I do that if I need it?
Update 3: checking the request type of my sending post.
Now I am checking the type of the request. Because I am having the same problem with the PUT/POST requests. So If can solved the problem with the put maybe all the problems will be solved.
When I execute the request and asking and inspect the request it is sending the the type (PUT/POST) but in the server php only detect or GET?? (the below example is using POST and the behavior is the same)
Call<UpdateResponse> requestCall = client.updateMedia(downloadItemList);
Log.i("CCC", requestCall .request().toString());
And the output is a POST:
Request{method=POST, url=http://myserver/api/v1/media/updateMedia.php, tag=null}
so I am sending a POST (no matter if I send a PUT) request to the sever but why in the server I am receiving a GET. I am locked!!! I don't know where is the problem.
Update 4: godaddy hosting.
I have my php server hosting on godaddy. Is there any problem with that? I create a local host and everything works pretty good but the same code is not working on godaddy. I did some research but I didn't find any good answer to this problem so Is possible that godaddy hosting is the problem?
PHP doesn't recognize anything other than GET and POST. the server should throw at you some kind of error like empty request.
To access PUT and other requests use
$putfp = fopen('php://input', 'r'); //will be a JSON string (provided everything got sent)
$putdata = '';
while($data = fread($putfp, filesize('php://input')))
$putdata .= $data;
fclose($putfp);
//php-like variable, if you want
$_PUT = json_decode($putdata);
did not tested, but should work.
I guess the problem is that you don't pass any data along with PUT request, that's why PHP recognizes the request as a GET. So I think you just need to try to pass some data using #FormUrlEncoded, #Multipart or probably #Body annotations
To add header in your retrofit2 you should create an interceptor:
Interceptor interceptor = new Interceptor() {
#Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException
{
okhttp3.Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("Content-Type", "application/x-www-form-urlencoded");
ongoing.addHeader("Accept", "application/json");
return chain.proceed(ongoing.build());
}
};
and add it to your client builder:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
PHP recognises 'PUT' calls. Extracted from PHP.net:
'REQUEST_METHOD' Which request method was used to access the page;
i.e. 'GET', 'HEAD', 'POST', 'PUT'.
You don't need to send any header if your server isn't expecting any
header.
Prior to use Retrofit or any other networking library, you should check the endpoint using a request http builder, like Postman or Advanced Rest Client. To debug the request/response when running your app or unit tests use a proxy like Charles, it will help you a lot to watch how your request/response really looks.
One of my partners has an API service which should send an HTTP POST request whenever a new file is published. This requires me to have an api file which will get the POST this way:
http://myip:port/api/ReciveFile
and requesting that the JSON format request should be:
{
"FILE ":"filename.zip",
"FILE_ID":"123",
"FILE_DESC":"PRUPOUS_FILE",
"EXTRAVAR":"",
"EXTRAVAR2":"",
"USERID":" xxxxxxxxxxxx",
"PASSWORD":"yyyyyyyyyyy"
}
Meanwhile it should issue a response, in JSON format if it got the file or not
{"RESULT_CODE":0,"RESULT_DESCR":""}
{"RESULT_CODE":1001,"RESULT_DESCR":"Bad request"}
And after, when I am finished elaborating the file, I should send back the modified file same way.
The question is, now basically from what I understand he will send me the variables witch I have to read, download the file, and send a response back.
I am not really sure how to do this any sample code would be welcomed!
I'm not sure exactly what the question is, but if you mean creating a success response in JSON for if an action occurred while adding data to it which is what can be understood from the question, just create an array with the values you wish to send back to the provider and do json_encode on the array which should create json and just print it back as a response.
About receiving the information; all you have to do is use the integrated curl functions or use a wrapper (Guzzle, etc) to output the raw JSON or json_decode data into a variable and do whatever you please with it.
From what I read in the question, you wish to modify the contents of it. This can be achieved by just decoding the json and changing the variables in the array, then printing the modified JSON back as a response.
Example (this uses GuzzleHTTP as an example):
$res = $client->request('GET', 'url');
$json = $res->getBody();
$array = json_decode($json, 1); // decode the json
// Start modifying the values or adding
$array['value_to_modify'] = $whatever;
$filename = $array['filename']; // get filename
// make a new request
$res = $client->request('GET', 'url/'.$filename);
// get the body of specified filename
$body = $res->getBody();
// Return the array.
echo json_encode($body);
References:
http://docs.guzzlephp.org/en/latest/
I am using slim php framework for developing REST API. I am successful in implementing POST and GET requests. I am using ContentTypes middleware as well to parse the JSON body in POST and PUT requests however my PUT request always gives empty string on the server. POST just works fine and I can get the parsed JSON as PHP associative array but cant get it in PUT request. I am using application/json in headers and I dont want to use application/x-www-form-urlencoded method.
$app->map('/example/:id', function ($id) use($app, $log) {
//$body = $app->request()->getBody();
//using the above in other POST calls & it works but does not in this case
$body = json_decode($app->request()->getBody()); //tried this. no success
var_dump($body);
} )->via ( 'PUT', 'PATCH' );
I am calling it via CURL like this
$headers = array(
'Content-Type'=>'application/json;charset=utf-8',
);
$id = 123;
$body = array("name"=>"myfirstname","email"=>"myemail");
$json_str = json_encode($body);
$response = Requests::put($base_url.'/api/v1/example/'.$id,$headers,$json_str);
When I try to return the same JSON from the API it returns empty array. I tried POSTMAN on chrome and above code but does not work. What is the issue.
Update: I have verified the same code works on localhost but does not work on remote dev server. What can be the reason? Do I need to alter any settings on server?
Slim reads php://input to get the contents of the request body, so whatever the problem is it has to do with the particulars of that stream.
Do you have some other code that tries to read php://input? If so, note that this is only possible starting from PHP 5.6 (which your local machine may have when your server does not).
Try using getInstance().
$body = json_decode($app->getInstance()->request()->getBody());
I'm just a newbie in the Slim framework. I've written one API using Slim framework.
A POST request is coming to this API from an iPhone app. This POST request is in JSON format.
But I'm not able to access the POST parameters that are sent in a request from iPhone. When I tried to print the POST parameters' values I got "null" for every parameter.
$allPostVars = $application->request->post(); //Always I get null
Then I tried to get the body of a coming request, convert the body into JSON format and sent it back as a response to the iPhone. Then I got the parameters' values but they are in very weird format as follows:
"{\"password\":\"admin123\",\"login\":\"admin#gmail.com\",\"device_type\":\"iphone\",\"device_token\":\"785903860i5y1243i5\"}"
So one thing for sure is POST request parameters are coming to this API file. Though they are not accessible in $application->request->post(), they are coming into request body.
My first issue is how should I access these POST parameters from request body and my second issue is why the request data is getting displayed into such a weird format as above after converting the request body into JSON format?
Following is the necessary code snippet:
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
//Instantiate Slim class in order to get a reference for the object.
$application = new \Slim\Slim();
$body = $application->request->getBody();
header("Content-Type: application/json");//setting header before sending the JSON response back to the iPhone
echo json_encode($new_body);// Converting the request body into JSON format and sending it as a response back to the iPhone. After execution of this step I'm getting the above weird format data as a response on iPhone.
die;
?>
Generally speaking, you can access the POST parameters individually in one of two ways:
$paramValue = $application->request->params('paramName');
or
$paramValue = $application->request->post('paramName');
More info is available in the documentation: http://docs.slimframework.com/#Request-Variables
When JSON is sent in a POST, you have to access the information from the request body, for example:
$app->post('/some/path', function () use ($app) {
$json = $app->request->getBody();
$data = json_decode($json, true); // parse the JSON into an assoc. array
// do other tasks
});
"Slim can parse JSON, XML, and URL-encoded data out of the box" - http://www.slimframework.com/docs/objects/request.html under "The Request Body".
Easiest way to handle a request in any body form is via the "getParsedBody()". This will do guillermoandrae example but on 1 line instead of 2.
Example:
$allPostVars = $application->request->getParsedBody();
Then you can access any parameters by their key in the array given.
$someVariable = $allPostVars['someVariable'];
Slim will json_decode the post body for you using this middleware
https://www.slimframework.com/docs/v4/middleware/body-parsing.html