C# WebException 响应解析问题

发布于 2025-01-18 12:00:14 字数 2061 浏览 0 评论 0原文

我正在对第三方 API 进行 API 调用,代码片段用于发出请求并将响应正文从响应中提取到 .Net 3.1 中的字符串中。 我可以正常且成功地解析成功的响应。直到昨天我们都能够解析 WebException 响应,现在它们只是在下面返回乱码字符串。

public dynamic RequestSender(HttpWebRequest request, dynamic vm)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(JsonConvert.SerializeObject(vm));
            request.ContentLength = byteArray.Length;
            request.ContentType = @"application/json; ";
            try
            {
                System.IO.Stream os = request.GetRequestStream();
                os.Write(byteArray, 0, byteArray.Length); //Push it out there
                os.Close();
                System.Net.WebResponse resp = request.GetResponse();
                System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                var responseString = sr.ReadToEnd().Trim();
                return responseString;
            }
            catch (WebException webErr)
            {
                return webErr;
                System.IO.StreamReader sr = new System.IO.StreamReader(webErr.Response.GetResponseStream());
                var responseString = sr.ReadToEnd().Trim();
                return responseString;
            }
            catch (Exception err)
            {
                return err;
            }
        }

预期的响应应该是:

{
    "response": {
        "errors": [
            {
                "code": "111285",
                "message": "The postal code F3FKWFIOJEF is invalid for CA United States."
            }
        ]
    }
}

但是我们得到的响应是:我们

"\u001f�\b\0\0\0\0\0\0\u0003\u0014�A\n�0\u0010\u0005Ы\f�\u00161�������E�|�@L�L\u0012)�w�n\u001f��\n[r2��\u0019�Y��G�)���9w:_��o��ן�3��K��W�\"J����\"9�\u0018�䛗��\b�J���A\U00069c02@\u0006m2���s�~\0\0\0��\u0003\0\u0010A�(\u007f\0\0\0"

尝试过的:

我们尝试更改请求,更改流读取器用于解析响应正文的编码,同时确保响应正文具有长度,确实如此。

不确定它可能是什么,因为第三方 API 在其实现中很不寻常,因为它将响应正文附加到 400 Bad Request 错误中。

I am making an API call to a third party API, the code snippet was made to make a request and extract the response body from the response into a string in .Net 3.1.
I can parse successful responses normally and successfully. We were able to parse WebException responses up to yesterday, where now they just return garbled string down below.

public dynamic RequestSender(HttpWebRequest request, dynamic vm)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(JsonConvert.SerializeObject(vm));
            request.ContentLength = byteArray.Length;
            request.ContentType = @"application/json; ";
            try
            {
                System.IO.Stream os = request.GetRequestStream();
                os.Write(byteArray, 0, byteArray.Length); //Push it out there
                os.Close();
                System.Net.WebResponse resp = request.GetResponse();
                System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                var responseString = sr.ReadToEnd().Trim();
                return responseString;
            }
            catch (WebException webErr)
            {
                return webErr;
                System.IO.StreamReader sr = new System.IO.StreamReader(webErr.Response.GetResponseStream());
                var responseString = sr.ReadToEnd().Trim();
                return responseString;
            }
            catch (Exception err)
            {
                return err;
            }
        }

The expected response should be:

{
    "response": {
        "errors": [
            {
                "code": "111285",
                "message": "The postal code F3FKWFIOJEF is invalid for CA United States."
            }
        ]
    }
}

However we are getting this as a response:

"\u001f�\b\0\0\0\0\0\0\u0003\u0014�A\n�0\u0010\u0005Ы\f�\u00161�������E�|�@L�L\u0012)�w�n\u001f��\n[r2��\u0019�Y��G�)���9w:_��o��ן�3��K��W�\"J����\"9�\u0018�䛗��\b�J���A\U00069c02@\u0006m2���s�~\0\0\0��\u0003\0\u0010A�(\u007f\0\0\0"

What we've tried:

We've tried altering the request, altering the encoding that streamreader uses to parse the response body, alongside making sure that the response body has length, which it does.

Not sure what it could be as the third party API is unusual in its implementation in that it attaches a response body into a 400 Bad Request error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撕心裂肺的伤痛 2025-01-25 12:00:14

经过大量的搜索和挖掘,我能够在创建httpwebrequest的背景某个地方时,可以自动解压缩GZIP以进行响应。
但是,在一定不确定的时间点之后,该指令被排除在外,这导致了解析错误。
事实证明,这不是编解码器,铸型类型或响应调用的结果,但是“ Deflate Gzip”之后不再是该请求的一部分。

我们的修复程序是通过确保添加来解决的:

request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

我还将代码的底部放到了那里,以便良好的方法。

request.KeepAlive = true;

多亏了这篇文章节省了几个小时的融化: http调用正在返回响应中的垃圾数据

After a lot of searching and digging I was able to determine that previously when creating the HttpWebRequest somewhere in the background it knew to automatically decompress Gzip for the responses.
However, after some indeterminate point in time, that instruction was left out which resulted in parsing errors.
Turns out it wasn't the result of incorrect codecs, or casting types or response calls, but that "Deflate Gzip" wasn't part of the request anymore afterwards.

Our fix was solved by making sure to add:

request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

I also threw in the bottom chunk of code down there for good measure.

request.KeepAlive = true;

Thanks to this post for saving hours of frustation: HTTP call in C# is returning garbage data in the response

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文