gpt4 book ai didi

c# - 如何在 C# 中使用 HttpClient GetAsync 方法传递请求内容

转载 作者:行者123 更新时间:2023-12-02 14:48:56 25 4
gpt4 key购买 nike

如何在 HttpClient.GetAsync 方法中传递请求内容?我需要根据请求内容获取数据。

[HttpGet]
public async Task<HttpResponseMessage> QuickSearch()
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
HttpResponseMessage response =await client.GetAsync("http://localhost:8080/document/quicksearch");

if (response.IsSuccessStatusCode)
{
Console.Write("Success");
}

最佳答案

如果您使用的是 .NET Core,标准的 HttpClient 可以开箱即用。例如,要发送带有 JSON 正文的 GET 请求:

HttpClient client = ...

...

var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("some url"),
Content = new StringContent("some json", Encoding.UTF8, ContentType.Json),
};

var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();

var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

关于c# - 如何在 C# 中使用 HttpClient GetAsync 方法传递请求内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57006372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com