【发布时间】: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