c# -从HttpWebResponse接收奇怪的字符
本文关键字:字符 HttpWebResponse | 更新日期: 2023-09-27 18:16:27
我有这个代码发送一个HTTP请求:
public string MakeRequest(string requestUrl, object data)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.ContentType = "application/json";
request.KeepAlive = false;
request.Headers.Add("Authorization", "BEARER " + apiToken);
System.Net.ServicePointManager.Expect100Continue = false;
if (data != null)
{
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(data);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
}
else
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
string Charset = response.CharacterSet;
Encoding encoding = Encoding.GetEncoding(Charset);
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
return reader.ReadToEnd();
}
}
它适用于大多数呼叫,但一个POST
,我收到这个响应:
"�'b'0'0'0'0'0'0�V�M,.I-�/JI-R��V3<S����L�L,�L��jk[���&'0'0'0"
当我看到Fiddler捕获的调用时,它说例程收到了:
{
"MasterOrder": {
"OrderId": "65250824"
}
}
那么,到底发生了什么?为什么提琴手看到一个响应而应用程序看到另一个响应?
通过将这些行添加到request
来解决这个问题:
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;