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"のようなcreate応答が得られました。 }ここに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

PHP関数file_get_contentsは、応答の内容全体を取得します。は必要ありません$res = stream_get_contents($fp)。応答はすでににあり$fpます。

あなたはこれを行うことができます:

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