почему file_get_contents ничего не получает от веб-службы? - PullRequest
2 голосов
/ 12 августа 2010

мы используем file_get_contents для связи с веб-сервисом, который создает пользователей и, в случае успеха, возвращает объект 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);
}

Сначала мы думали, что веб-сервис должен был ничего не возвращать, поэтому мы протестировали его на c #, который работал совершенно нормально, то есть мы получили ответ create что-то вроде {"stutas": "success","userCreated": "true"} вот код 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?

1 Ответ

1 голос
/ 12 августа 2010

Функция PHP file_get_contents получит все содержимое ответа.Вам не нужно $res = stream_get_contents($fp).Ответ уже будет в $fp.

. Вы можете просто сделать это:

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