I'm trying to send an request to an Self-Hosted WCF-Service with REST in PHP. I want to send the object to the WCF service as an JSON Object. I did not get it running yet. Has anyone an example how to call the service out of PHP?
This is the Operation contract (The method is a POST method):
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void Method1(AnObject object);
The best working Code in PHP is the following:
$url = "http://localhost:8000/webservice/Method1?object=$object";
$url1 = parse_url($url);
// extract host and path:
$host = $url1['host'];
$path = $url1['path'];
$port = $url1['port'];
// open a socket connection on port 80 - timeout: 30 sec
$fp = fsockopen($host, $port, $errno, $errstr, 30);
if($fp)
{
// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-type: application/json \r\n");
fputs($fp, "Content-length: ". strlen($object) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $object);
//
// $result = '';
// while(!feof($fp)) {
// // receive the results of the request
// $result .= fgets($fp, 128);
// }
}
else {
return array(
'status' => 'err',
'error' => "$errstr ($errno)"
);
}
// close the socket connection:
fclose($fp);
But this code does not send the object. In Debugging-Mode the Object is "null". I just see, that it enters the method.
Very important is JSON format.
I got work "der_chirurg" solution by adding parameter next to $path as below
original:
changed to:
and instead of in the $url
Finally:
I found the solution for my own problem:
When you perform a POST on a WCF Rest service the raw request should look as below:
Assuming your
AnObject
looks as below:From your php code you are trying to send the object as a query string which is not going to work. Rather build your code to add the json string to the http body.
Use some tools like Fiddler or WireShark where you can intercept the request/response and inspect them. You can use them even to test the WCF Rest service by building a raw request.
Find some links that might be helpful:
Create a php Client to invoke a REST Service
php rest api call