English 中文(简体)
如何从PHP调用节约的 WCF-Services
原标题:How to call RESTful WCF-Service from 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方法):

[OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    void Method1(AnObject object);

PHP中的最佳工作守则如下:

$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
");
    fputs($fp, "Host: $host
");

    fputs($fp, "Content-type: application/json 
");
    fputs($fp, "Content-length: ". strlen($object) ."
");
    fputs($fp, "Connection: close

");
    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);

但此代码不会发送对象。 在调试模式中, 对象是“ null ” 。 我只是看到它进入了方法 。

最佳回答

我找到了解决我自己问题的办法:

$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); 
问题回答

当您在休养假服务上执行POST时,原始请求应如下表所示:

POST http://localhost:8000/webservice/Method1 HTTP 1.1
Content-Type: application/json
Host: localhost

{"object":{"ObjectId":1,"ObjectValue":60}

假设您 如下所示:

[DataContract]
public class AnObject 
{
    [DataMember]
    public int ObjectId {get;set;}
    [DataMember]
    public int ObjectValue {get;set;}
} 

您正试图从您的php 代码中将对象发送为无效的查询字符串。 相反, 您正在构建代码, 以便将json 字符串添加到 http 体中 。

使用某些工具, 如 < a href=> http://www. fiddir2.com" rel = "nofollown noreferrer" > fiddler 或 < a href="http://www.wireshark.org" rel= "nofollown noreferrer" > WirreShark , 您可以拦截请求/ 回应并检查它们。 您可以使用它们来测试WCF休息服务, 建立原始请求 。

找到一些可能有用的链接 :

  1. 创建php客户端以援引 REST Service

  2. < a href=" "https://stackoverflow.com/ questions/3712183/php-rest-api-call" >php 休息电话

我找到了工作“der_chirurrrg”解决方案, 在 $path 旁边添加参数如下 。

原件:

$url = "http://localhost:8000/webservice/Method1?object=$object"; 
fputs($fp, "POST $path HTTP/1.1
");

更改为 :

fputs($fp, "POST $path**?object=$object** HTTP/1.1
");

and instead of in the $url

$url = "http://localhost:8000/webservice/Method1

最后:

 url = "http://localhost:8000/webservice/Method1";
        $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?value=test HTTP/1.1
");
    fputs($fp, "Host: $host
");

    fputs($fp, "Content-type: application/json 
");
    fputs($fp, "Content-length: ". strlen($param) ."
");
    fputs($fp, "Connection: close

");
 $jsonData = json_encode($object, JSON_PRETTY_PRINT);
 $options = array(
      http =>array(
             method         =>  "POST",
             ignore_errors  =>  true,
             content        =>  $jsonData,
             header         =>  "Content-Type: application/json
" .
                                "Content-length: ".strlen($jsonData)."
".
                                "Expect: 100-continue
" .
                                "Connection: close"
            )
        );

        $context = stream_context_create($options);
        $result = @file_get_contents($requestUrl, false, $context);

JSON格式很重要





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...