2

我们正在使用 file_get_contents 与创建用户的 Web 服务进行通信,如果成功,它将返回一个 JSON 对象,其中包含新创建的用户的详细信息。下面的代码展示了我们是如何做到的,用户已成功创建,这意味着我们可以从后端看到它,但是,我们无法获得 JSON 响应,它什么也没返回

public function register(){
    $username = "testing";
    $email = "testingemail@test.com";
    $password = "testpsd";

    $userData = '{"$xmlns": {"pluser": "http://xml.webservice.com/auth/data/User"},'
            .'"pluser$userName": "'.$username.'",'
            .'"pluser$password": "'.$password.'",'
            .'"pluser$fullName": "fullname",'
            .'"pluser$email": "'.$email.'"}';
    $url = 'https://webservice.com?form=json';
    $cparams = array('http' => array('method' => 'POST','ignore_errors' => true));
    $cparams['http']['content'] = $userData;      
    $cparams['http']['request_fulluri'] = true;
    $cparams['http']['header'] = 'Content-type: application/json';
    $context = stream_context_create($cparams);

    $fp = @file_get_contents($url,false,$context);$res = stream_get_contents($fp);
    print_r($res);
}

起初我们认为 Web 服务不应该返回任何内容,因此我们在 c# 中对其进行了测试,效果非常好,这意味着我们得到了类似 {"stutas":"successful","userCreated":"true" 的创建响应这里是 C# 代码:

String url = "https://webservice.com?form=json";
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(url);
        req.Method = "POST";

        string strRequest = "exactly the same json string";
        req.ContentLength = strRequest.Length;
        StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
        streamOut.Write(strRequest);
        streamOut.Close();
        StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
        while (!streamIn.EndOfStream)
            Console.WriteLine(streamIn.ReadToEnd());
        streamIn.Close();

        Console.ReadKey();}

php代码中是否有任何遗漏或配置错误?

4

1 回答 1

1

The PHP function file_get_contents will get the entire contents of the response. You don't need the $res = stream_get_contents($fp). The response will already be in $fp.

You can just do this:

$fp = @file_get_contents($url,false,$context);
print_r($fp);
于 2010-08-12T01:43:39.720 回答