C#:从HTTP 409冲突响应获取消息正文

时间:2018-09-04 07:29:39

标签: c# mono chunked-encoding

我正在尝试从Web服务(位于http://www.ekkuli.net/conflict_call.php)获取消息正文,该Web服务使用以下代码返回“ Transfer-Encoding:chunked”标签和409冲突响应:

String webAddr = "http://www.ekkuli.net/conflict_call.php";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.ServicePoint.Expect100Continue = false;
httpWebRequest.Accept = "application/json";
httpWebRequest.KeepAlive = true;

try {
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
        String myJson = "{ \"method\" : \"just testing\" }";
        streamWriter.Write(myJson);
        streamWriter.Flush();
     }

     var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

     using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
         var responseText = streamReader.ReadToEnd(); 
      }
} catch (WebException ex) { // Catch 409 Conflict response
    try {
        // Try to get message body from 409 Response
        var s = ex.Response.GetResponseStream();
        var sr = new System.IO.StreamReader(s);
        var content = sr.ReadToEnd(); // THIS THROWS AN EXCEPTION
    } catch (Exception excep) {
        // Exception! Error getting response stream (ReadAsync): ReceiveFailure Value cannot be null. 
    }
}

当服务器返回“ Transfer-encoding:Chuncked” -header时,是否有任何方法可以从409 Conflict -response获取响应主体?如果禁用此标头并返回Content-length,则一切正常,但是在这种情况下,我无法修改服务器代码。

尝试使用RestSharp -library时,会发生相同的问题(它返回状态代码0和消息正文0)。

我正在使用Mono(适用于Mac)

0 个答案:

没有答案