我们正在使用file_get_contents与创建用户的Web服务进行通信,如果成功,它将返回一个JSON对象和新创建的用户的详细信息。 下面的代码显示了我们如何做到这一点,用户已成功创建,这意味着我们可以从后端看到它,但是,我们无法获得JSON响应,它不会返回。为什么file_get_contents从Web服务中什么都没有得到?
public function register(){
$username = "testing";
$email = "[email protected]";
$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”回应:“成功的”, “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($用户数据))'? – 2010-08-27 04:32:55
@Peter,我终于设法使用curl来解决这个问题。 curl起初不工作,因为php设置是错误的。一旦这个问题得到解决,一切都会像魅力一样工作。 非常感谢 – walter 2010-08-30 01:41:32