【问题标题】:why does file_get_contents get nothing from the web service?为什么 file_get_contents 从 Web 服务中得不到任何信息?
【发布时间】:2010-08-12 01:39:51
【问题描述】:

我们正在使用 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": “真的”} 这是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 代码中是否有任何遗漏或配置错误?

【问题讨论】:

  • 您是否验证了 JSON 确实是您认为它使用的 print_r(json_decode($userData))
  • @Peter,我终于设法使用 curl 解决了这个问题。 curl 起初不起作用,因为 php 设置错误。一旦解决了这个问题,一切都像魅力一样。还是谢谢

标签: php web-services json file-get-contents


【解决方案1】:

PHP 函数file_get_contents 将获取响应的全部内容。您不需要$res = stream_get_contents($fp)。回复已经在$fp

你可以这样做:

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

【讨论】:

  • 太好了!非常感谢!我得到了响应,但这是一个 java 异常。鉴于传入的url和数据完全相同,为什么它会返回异常?为什么这在 c# 中工作得很好?
  • 这可能与您的 Web 后端有关。您可以尝试删除 content-type 标头并将其替换为 content-length 标头,这将使其更接近 C# 代码。
  • 如果我用内容长度标头替换内容类型标头,它将返回“不支持的内容异常”。这真的很奇怪。我还是不明白为什么同一个web服务接受通过c#而不是php发送的post请求,这没有意义...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
相关资源
最近更新 更多