2010-08-12 111 views
2

我们正在使用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代码?

+0

您是否验证了JSON是真的你认为它是使用'的print_r(json_decode($用户数据))'? – 2010-08-27 04:32:55

+0

@Peter,我终于设法使用curl来解决这个问题。 curl起初不工作,因为php设置是错误的。一旦这个问题得到解决,一切都会像魅力一样工作。 非常感谢 – walter 2010-08-30 01:41:32

回答

1

PHP函数file_get_contents将得到响应的全部内容。你不需要$res = stream_get_contents($fp)。回应将已在$fp

你可以只是这样做:

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

太棒了!非常感谢! 我有回应,但它是一个Java异常。 为什么它返回一个异常,因为传入的url和数据完全相同?为什么这在c#中完美无缺? – walter 2010-08-12 01:58:29

+0

这可能与您的网络后端有关。您可以尝试删除内容类型标题并用内容长度标题替换它,这将使它更接近C#代码。 – 2010-08-12 02:11:24

+0

如果我用内容长度标题替换内容类型标题,它将返回“不支持的内容异常”。这真的很奇怪。我仍然不明白为什么相同的Web服务接受通过C#发送的请求,但不是PHP,它没有任何意义。 – walter 2010-08-12 02:57:53