在PHP中通过REST流式传输JSON

时间:2015-03-09 16:31:37

标签: c# php json rest stream

我在C#中进行流式网络服务调用,如下所示:

public static HttpWebRequest GetRequest(string requestUri, string method, IEnumerable<string> content, bool useCantor)
    {
        HttpWebRequest request = HttpWebRequest.Create(requestUri) as HttpWebRequest;
        request.Method = method;
        request.ContentType = "application/json";
        request.AllowWriteStreamBuffering = false;
        request.SendChunked = true;
        request.Timeout = 3600 * 1000;

        RequestManager.GenerateSignature(request, true, useCantor);

        using (Stream stream = request.GetRequestStream())
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(stream))
        {
            foreach (string input in content)
            {
                sw.WriteLine(input);
                sw.Flush();
            }
        }

        return request;
    }

我已将此翻译成PHP,如下所示:

        $options = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>"Content-type: application/json\r\n" .
              "Authorization: hmac " .$accesstoken . "\r\n" . 
              "Content-length: " . $contentlength
    )
    );

    //open stream

    $context=stream_context_create($options);
    $fp = fopen('http://uri-of-service', 'rb', false, $context);

    //write data
    fwrite($context,'MAIL|SURNAME');
    fflush($fp);
    fwrite($context,json_encode(array( 'MAIL' => 'mail1@mail.se','SURNAME' => 'sur1')));
    fflush($fp);
    fwrite($context,json_encode(array( 'MAIL' => 'mail2@mail.se','SURNAME' => 'sur2')));
    fflush($fp);
    fwrite($context,json_encode(array( 'MAIL' => 'mail3@mail.se','SURNAME' => 'sur3')));
    fflush($fp);

//close
fclose($context);

然而,我迟到了

  

无法打开流:HTTP请求失败

如何正确翻译C#代码?

0 个答案:

没有答案