早上我遇到了一个问题,我调用的 API 是 Get 方法,但是为了从中获取数据,我必须发送 json body。在 Postman 中测试时效果很好,但是在我的项目中使用 HttpClient 调用时无法实现。
以下是 post 的屏幕截图:
此外,它还有一个 Bearer Token,我会在 Authorization 中传递。
现在,当我尝试在客户端实现它时,这是我的代码:
以下是 post 的屏幕截图:
![enter image description here](https://istack.dev59.com/Odtcr.webp)
现在,当我尝试在客户端实现它时,这是我的代码:
var stringPayload = JsonConvert.SerializeObject(json);
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://myapiendpoint/serviceability/"),
Content = new StringContent(stringPayload, Encoding.UTF8, "application/json"),
};
var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
当我使用这段代码调用此方法时,我会得到以下结果:
System.Net.HttpStatusCode.MethodNotAllowed - Status code 405
我也尝试更改了这一行
Method = HttpMethod.Get to Method = HttpMethod.Post
但仍然遇到相同的错误
我知道这是API端糟糕的实现,理想情况下应该使用POST请求,但更改不在我的掌控之中,因此需要找到解决方案。