简体   繁体   English

C# HttpClient GetAsync 异常“服务器返回无效或无法识别的响应”

[英]C# HttpClient GetAsync exception “The server returned an invalid or unrecognized response”

This seems to be a random issue.这似乎是一个随机问题。 Sometimes the GetAsync successfully gets a response (200/OK).有时 GetAsync 会成功获得响应 (200/OK)。 Other times it throws an exception.其他时候它会抛出异常。 I'm thinking it has something to do with the "Transfer-Encoding: chunked".我认为这与“传输编码:分块”有关。 BTW...the streamed files are anywhere from 8MB to 300MB顺便说一句...流式文件的大小从 8MB 到 300MB

Here is my pertinent code:这是我的相关代码:

HttpResponseMessage response = null;
try
{
    HttpClient httpClient = new HttpClient
    {
        Timeout = TimeSpan.FromSeconds(60)
    };
    httpClient.DefaultRequestHeaders.Add("Accept", "multipart/related; type=\"application/dicom\"");
    response = await httpClient.GetAsync(uri);
    if (response.StatusCode != HttpStatusCode.OK)
    {
        Console.WriteLine($"Response:[{response}]");
        return false;
    }
}
catch (Exception e)
{
    Console.WriteLine($"Exception:[{e.Message}] | Stack:[{e.StackTrace}] | InnerEx:[{e.InnerException}]");
    return false;
}

Here's the HttpResponseMessage when GetAsync is successful (200/OK):这是 GetAsync 成功(200/OK)时的 HttpResponseMessage:

{
  "Version": {
    "Major": 1,
    "Minor": 1,
    "Build": -1,
    "Revision": -1,
    "MajorRevision": -1,
    "MinorRevision": -1
  },
  "Content": {
    "Headers": [
      {
        "Key": "Content-Type",
        "Value": [ "multipart/related; boundary=Boundary_77_676776408_1611644859244; type=\"application/dicom\"" ]
      }
    ]
  },
  "StatusCode": 200,
  "ReasonPhrase": "OK",
  "Headers": [
    {
      "Key": "Transfer-Encoding",
      "Value": [ "chunked" ]
    },
    {
      "Key": "MIME-Version",
      "Value": [ "1.0" ]
    },
    {
      "Key": "Date",
      "Value": [ "Tue, 26 Jan 2021 07:07:39 GMT" ]
    },
    {
      "Key": "Proxy-Connection",
      "Value": [ "Keep-Alive" ]
    },
    {
      "Key": "Connection",
      "Value": [ "Keep-Alive" ]
    },
    {
      "Key": "Age",
      "Value": [ "0" ]
    }
  ],
  "RequestMessage": {
    "Version": {
      "Major": 2,
      "Minor": 0,
      "Build": -1,
      "Revision": -1,
      "MajorRevision": -1,
      "MinorRevision": -1
    },
    "Content": null,
    "Method": { "Method": "GET" },
    "RequestUri": "http://1.2.3.4:5007/blah/blah1/11/blah2/22/blah3/33",
    "Headers": [
      {
        "Key": "Accept",
        "Value": [ "multipart/related; type=\"application/dicom\"" ]
      }
    ],
    "Properties": {}
  },
  "IsSuccessStatusCode": true
}

Other times there is no response and an exception is thrown:其他时候没有响应并抛出异常:

Exception:[The server returned an invalid or unrecognized response.] |异常:[服务器返回无效或无法识别的响应。] | Stack:[ at System.Net.Http.HttpConnection.ThrowInvalidHttpResponse() at System.Net.Http.HttpConnection.ChunkedEncodingReadStream.ReadChunkFromConnectionBuffer(Int32 maxBytesToRead, CancellationTokenRegistration cancellationRegistration) at System.Net.Http.HttpConnection.ChunkedEncodingReadStream.CopyToAsyncCore(Stream destination, CancellationToken cancellationToken) at System.Net.Http.HttpConnection.HttpConnectionResponseContent.SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken) at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Z27226C864BAC7454A850 Stack:[ at System.Net.Http.HttpConnection.ThrowInvalidHttpResponse() at System.Net.Http.HttpConnection.ChunkedEncodingReadStream.ReadChunkFromConnectionBuffer(Int32 maxBytesToRead, CancellationTokenRegistration cancellationRegistration) at System.Net.Http.HttpConnection.ChunkedEncodingReadStream.CopyToAsyncCore(Stream destination, CancellationToken cancellationToken) at System.Net.Http.HttpConnection.HttpConnectionResponseContent.SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken) at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer) at System.Net.Http.HttpClient .FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage 请求, CancellationTokenSource cts, Z27226C864BAC7454A850 4F8EDB15D95BZ disposeCts) at myapp.GetBlahAsync(Uri uri, String newFileName) in C:\blah\Svc.cs:line 97] | 4F8EDB15D95BZ disposeCts) 在 myapp.GetBlahAsync(Uri uri, String newFileName) 在 C:\blah\Svc.cs:line 97] | InnerEx:[]内壳:[]

is because you need deserialize response是因为你需要反序列化响应

   HttpResponseMessage response = null;
try
{
    HttpClient httpClient = new HttpClient {
        Timeout = TimeSpan.FromSeconds(60)
    };
    httpClient.DefaultRequestHeaders.Add("Accept", "multipart/related; type=\"application/dicom\"");
    response = await httpClient.GetAsync(uri);
    if (response.IsSuccessStatusCode)
    {

        var responseData = await response.Content.ReadAsStringAsync();
        var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
        var result = JsonSerializer.Deserialize<Root>(responseData, options);

        Console.WriteLine($"Response:[{result }]");
        return result;
    }
}
catch (Exception e)
{
    Console.WriteLine($"Exception:[{e.Message}] | Stack:[{e.StackTrace}] | InnerEx:[{e.InnerException}]");
    return false;
}

for convert your json to c# class use this site Json to c# class for convert your json to c# class use this site Json to c# class

  // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
        public class Version    {
            public int Major { get; set; } 
            public int Minor { get; set; } 
            public int Build { get; set; } 
            public int Revision { get; set; } 
            public int MajorRevision { get; set; } 
            public int MinorRevision { get; set; } 
        }
    
        public class Header    {
            public string Key { get; set; } 
            public List<string> Value { get; set; } 
        }
    
        public class Content    {
            public List<Header> Headers { get; set; } 
        }
    
        public class Method    {
            public string Method { get; set; } 
        }
    
        public class Properties    {
        }
    
        public class RequestMessage    {
            public Version Version { get; set; } 
            public object Content { get; set; } 
            public Method Method { get; set; } 
            public string RequestUri { get; set; } 
            public List<Header> Headers { get; set; } 
            public Properties Properties { get; set; } 
        }
    
        public class Root    {
            public Version Version { get; set; } 
            public Content Content { get; set; } 
            public int StatusCode { get; set; } 
            public string ReasonPhrase { get; set; } 
            public List<Header> Headers { get; set; } 
            public RequestMessage RequestMessage { get; set; } 
            public bool IsSuccessStatusCode { get; set; } 
        }

or in visual studio in Edit-->Paste Special-->Paste JSON As Classes或在 Visual Studio 中的Edit-->Paste Special-->Paste JSON As Classes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HttpClient中“服务器返回无效或无法识别的响应”的含义 - Meaning of “The server returned an invalid or unrecognized response” in HttpClient 是什么原因导致HttpClient中出现“ WinHttpException:服务器返回了无效或无法识别的响应”? - What causes “WinHttpException: The server returned an invalid or unrecognized response” in HttpClient? 拦截C#HttpClient GetAsync - Intercept C# HttpClient GetAsync HttpClient.GetAsync,无效的URI异常 - HttpClient.GetAsync, Invalid URI exception c# - 通过 HttpClient 运行 HTTP POST 时无法识别的响应? - c# - Unrecognized response when run HTTP POST via HttpClient? Xamarin forms 和 gRPC:服务器返回无效或无法识别的响应 - Xamarin forms and gRPC: The server returned an invalid or unrecognized response SSIS C# HTTP GetAsync 不等待响应 - SSIS C# HTTP GetAsync not waiting for the response 如何在 c# 中使用 HttpClient GetAsync 方法传递请求内容 - How to pass request content with HttpClient GetAsync method in c# httpClient.GetAsync 中的 Memory 泄漏 C# .NET 4.8 - Memory leak in httpClient.GetAsync C# .NET 4.8 gRPC客户端 - &gt;服务器连接失败 - 服务器返回无效或无法识别的响应 - gRPC Client->Server connection failed - The server returned an invalid or unrecognized response
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM