HttpClient 的 PutAsync 行为不同于手动 PUT 请求(通过 PostMan)
HttpClient's PutAsync behaving differently than a manual PUT request (via PostMan)
我正在尝试创建一个到外部 API 的 PUT 请求,并将整数数组作为请求正文。当直接通过 PostMan(Chrome 扩展名)发布到有问题的外部 API 时,它工作正常。这是请求:
PUT /rest/*****?skipconfig=true HTTP/1.1
Host: ******:****
Authorization: Basic **********
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache
[1214186,1214052,1214333,1213983,1214332,1214332]
但是,当我尝试使用 .NET 的 HttpClient 创建相同的请求时,外部 API 在大约 10 秒后抛出服务器错误 500,这让我怀疑 HttpClient 已经以某种模糊的方式更改了请求方式,这使得外部 API 读取请求错误。这是我的示例代码:
var json = JsonConvert.SerializeObject(intArray);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", SvcCredentials);
var content = new StringContent(json, Encoding.UTF8, MediaTypeHeaderValue.Parse("application/json; charset=utf-8").MediaType);
// List data response.
var uri = new Uri(BaseUrl + "/rest/*****?skipconfig=true", UriKind.Absolute);
HttpResponseMessage response = await client.PutAsync(uri, content);
if (response.IsSuccessStatusCode)
{
// Parse the response body.
return response.Content.ReadAsAsync<object>().ToString();
}
throw new Exception(response.StatusCode.ToString());
我在这里错过了什么?我尝试使用 URI 对象和 URL-string.
调用 PutAsync 方法
好的,所以我找到了这个问题的原因。
经过一些研究,我能够使用 fiddler 中的一个简单选项解密 HTTPS 请求。
事实证明,StringContent(json, Encoding.UTF8, MediaTypeHeaderValue.Parse("application/json; charset=utf-8").MediaType);
在幕后添加了一个 "Content-Length" header。这个header是导致另一端服务器错误的原因(不要问我为什么)。
我正在尝试创建一个到外部 API 的 PUT 请求,并将整数数组作为请求正文。当直接通过 PostMan(Chrome 扩展名)发布到有问题的外部 API 时,它工作正常。这是请求:
PUT /rest/*****?skipconfig=true HTTP/1.1
Host: ******:****
Authorization: Basic **********
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache
[1214186,1214052,1214333,1213983,1214332,1214332]
但是,当我尝试使用 .NET 的 HttpClient 创建相同的请求时,外部 API 在大约 10 秒后抛出服务器错误 500,这让我怀疑 HttpClient 已经以某种模糊的方式更改了请求方式,这使得外部 API 读取请求错误。这是我的示例代码:
var json = JsonConvert.SerializeObject(intArray);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", SvcCredentials);
var content = new StringContent(json, Encoding.UTF8, MediaTypeHeaderValue.Parse("application/json; charset=utf-8").MediaType);
// List data response.
var uri = new Uri(BaseUrl + "/rest/*****?skipconfig=true", UriKind.Absolute);
HttpResponseMessage response = await client.PutAsync(uri, content);
if (response.IsSuccessStatusCode)
{
// Parse the response body.
return response.Content.ReadAsAsync<object>().ToString();
}
throw new Exception(response.StatusCode.ToString());
我在这里错过了什么?我尝试使用 URI 对象和 URL-string.
调用 PutAsync 方法好的,所以我找到了这个问题的原因。
经过一些研究,我能够使用 fiddler 中的一个简单选项解密 HTTPS 请求。
事实证明,StringContent(json, Encoding.UTF8, MediaTypeHeaderValue.Parse("application/json; charset=utf-8").MediaType);
在幕后添加了一个 "Content-Length" header。这个header是导致另一端服务器错误的原因(不要问我为什么)。