【发布时间】:2021-03-15 12:24:12
【问题描述】:
我正在尝试发送 http GET 请求,但我收到 400 BadRequest。 我只需要有人确认我正确打包了请求。 我认为我的内容不好?
var um = "123456";
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{_iOptions.Server}{_iOptions.Method.GetData}")
};
request.Content = new ByteArrayContent(Encoding.UTF8.GetBytes("{ \"um\": " + um + " }"));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);
responseMessage.EnsureSuccessStatusCode();
GetResponse response = await responseMessage.Content.ReadAsAsync<GetResponse>();
if (response.Code == (int)System.Net.HttpStatusCode.OK)
{
response.Success = true;
return response;
}
else
{
response.Success = false;
return response;
};
【问题讨论】:
-
Bad Request 表示内容不符合 API 的要求。在不知道您的 API 的详细信息的情况下,我们只能猜测。我的猜测是您将 json 作为字节数组内容而不是字符串内容发送。
-
我知道@Crowcoder,但我没有这个 api 的任何详细规格。我会尝试作为 stringContent 发送,我会告诉你的。谢谢。
-
如果您使用的是 HTTP(不是 HTTPS),您可以使用像 wireshark 或 fiddler 这样的嗅探器来查看请求。
-
您确定是
Encoding.UTF8.GetBytes("{ \"um\": " + um + " }")而不是Encoding.UTF8.GetBytes("{ \"um\": \"" + um + "\" }")吗? -
@Crowcoder -- 使用
ByteArrayContent是完全可以接受的。我一直用它来发送 JSON。StringContent实际上是从ByteArrayContent派生的。看看the source。
标签: c# asp.net-core .net-core get httpclient