如何在 dotnet 中发送包含请求标头列表的帖子请求

How to send a post request in dotnet with a list of request headers

提问人:Concellia 提问时间:3/6/2022 最后编辑:SkinConcellia 更新时间:3/6/2022 访问量:6496

问:

    public static async Task<HttpResponseMessage> Post(string endPoint, string data){
        HttpContent c = new StringContent(data, Encoding.UTF8, "application/json");
        using (var client = new HttpClient())
        {
            HttpRequestMessage request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(VodapayBaseUrl + endPoint),
                Content = c,

            };

            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage result = await client.SendAsync(request).ConfigureAwait(false); // The code fails here

            if (result.IsSuccessStatusCode)
            {
                
                Console.WriteLine("got here");
                return result;
            }
            else
            {
                Console.WriteLine("failled");
                return result;
            }
        }
          
       // return result;
        
    }

这是更新版本:

public static async Task Post()
    {
        using (var httpClient = new HttpClient())
        {
            var requestString = "{\"authCode\": \"0000000001Nk1EEhZ3pZ73z700271891\" }";

            httpClient.BaseAddress = new Uri("https://bounties-backend-mini-program.herokuapp.com");

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var request = new HttpRequestMessage(HttpMethod.Post, $"/api/userInfo");
            request.Content = new StringContent(requestString, System.Text.Encoding.UTF8, "application/json");

            var response = await httpClient.SendAsync(request);
            var responseContent = await response.Content.ReadAsStringAsync();

            Console.WriteLine(JsonConvert.SerializeObject(response.Headers.ToList()));

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Successful");
                Console.WriteLine(responseContent);
            }
            else
            {
                Console.WriteLine("Not successful");
            }
        }


    }

    class Program
    {

        private static void Main(string[] args)
        {
           
            Post().Wait();
            Console.WriteLine();

        }
    }
}

有人可以帮忙解决这个问题吗,我是 c# 的新手,对编码相对陌生。我正在尝试使用 httpclient 发送请求,我需要以 json 格式发送数据,我还需要发送标头列表。我怎样才能做到这一点,并在最后返回json数据,您的帮助将不胜感激。运行此命令时出现错误:

enter image description here

C# .Net-Core HttpClient SendaSync

评论


答:

2赞 Skin 3/6/2022 #1

你的代码不远了,这是我在我的一个项目中的例子......

using (var httpClient = new HttpClient())
{
    var requestString = "{\"authCode\": \"0000000001Nk1EEhZ3pZ73z700271891\" }";

    // Setup the HttpClient and make the call and get the relevant data.
    httpClient.BaseAddress = new Uri("https://bounties-backend-mini-program.herokuapp.com");

    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var request = new HttpRequestMessage(HttpMethod.Post, $"/api/userInfo");
    request.Content = new StringContent(requestString, System.Text.Encoding.UTF8, "application/json");

    var response = await httpClient.SendAsync(request);
    var responseContent = await response.Content.ReadAsStringAsync();

    Console.WriteLine(JsonConvert.SerializeObject(response.Headers.ToList()));

    if (response.IsSuccessStatusCode)
    {
        Console.WriteLine("Successful");
        Console.WriteLine(responseContent);
    }
    else
    {
        Console.WriteLine("Not successful");
    }
}

...显然,它对手头的场景有不同程度的思考,但只是根据需要进行调整。

评论

0赞 Concellia 3/6/2022
非常感谢您的帮助,但我仍然收到同样的错误,当我尝试调试时,我的代码似乎立即停止在 var response = await httpClient.SendAsync(request);当它到达这里时,它会返回我发布的错误,我不确定这是否与我在 main 方法上调用它的方式有关,或者是否与我的 .NET Core 版本有关。
0赞 Skin 3/6/2022
端点是什么?也许我可以从这里测试。
0赞 Concellia 3/6/2022
很抱歉响应延迟,您可以使用此端点进行测试:“bounties-backend-mini-program.herokuapp.com/api/userInfo”,您可以只传递“{\”authCode\“: \”0000000001Nk1EEhZ3pZ73z700271891\“ }”作为您的json数据
0赞 Skin 3/6/2022
它回来了,我获得了成功。响应正文中没有内容,但有标题,它们看起来都是非常标准的东西......[{“key”:“服务器”,“值”:[“牛仔”]},{“key”:“连接”,“值”:[“保持活动”]},{“key”:“X-powered-by”,“值”:[“express”]},{“key”:“ETag”,“value”:[“w/\”2-vyGp6PvFo4RvsFtPoIWeCReyIC8\“”]},{“key”:“Date”,“Value”:[“Sun, 06 Mar 2022 09:41:54 GMT”]},{“key”:“Via”,“Value”:[“1.1 vegur”]}] ...那么一定与你的环境有关。对不起,我再也帮不上忙了。您可能需要回收您的 authCode。:-)
0赞 Concellia 3/6/2022
谢谢你的回答是正确的,这只是我为你制作的一个简单的测试,它没有任何数据,你使用的是哪个 .net 核心?我正在使用 .Net Core 3.1,您是否在此处传递了相同的端点 httpClient.BaseAddress 和此处 $“{slash}{urlSuffix}”?