如何从PHP调用RESTful WCF服务
问题描述:
我正在尝试使用PHP中的REST向自托管WCF服务发送请求. 我想将该对象作为JSON对象发送到WCF服务. 我还没有运行它. 有没有人举过一个例子,说明如何用PHP调用服务?
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?
这是运营合同"(该方法是POST方法):
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);
PHP中最好的代码如下:
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.
答
我为自己的问题找到了解决方案:
I found the solution for my own problem:
$url = "http://localhost:1234/service/PostMethod";
$jsonObject = json_encode($transmitObject);
$options = array(
CURLOPT_HTTPHEADER => array(
"Content-Type:application/json; charset=utf-8",
"Content-Length:".strlen($jsonObject)));
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => $url,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 4,
CURLOPT_POSTFIELDS => $jsonObject
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
curl_exec($ch);
curl_close($ch);