gpt4 book ai didi

C# - 如何从 http 请求中获取 HTTP 状态代码

转载 作者:行者123 更新时间:2023-11-30 20:25:03 25 4
gpt4 key购买 nike

我有以下代码,作为 POST 请求按预期工作(给定正确的 URL 等)。似乎我在读取状态代码时遇到了问题(我收到了成功的 201,并且根据该数字我需要继续处理)。知道如何获取状态代码吗?

static async Task CreateConsentAsync(Uri HTTPaddress, ConsentHeaders cconsentHeaders, ConsentBody cconsent)
{
HttpClient client = new HttpClient();

try
{
client.BaseAddress = HTTPaddress;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
client.DefaultRequestHeaders.Add("Connection", "keep-alive");
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");

client.DefaultRequestHeaders.Add("otherHeader", myValue);
//etc. more headers added, as needed...

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);

request.Content = new StringContent(JsonConvert.SerializeObject(cconsent, Formatting.Indented), System.Text.Encoding.UTF8, "application/json");

Console.WriteLine("\r\n" + "POST Request:\r\n" + client.DefaultRequestHeaders + "\r\nBody:\r\n" + JsonConvert.SerializeObject(cconsent, Formatting.Indented) + "\r\n");

await client.SendAsync(request).ContinueWith
(
responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result + "\r\nBody:\r\n" + responseTask.Result.Content.ReadAsStringAsync().Result);
}
);

Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error in " + e.TargetSite + "\r\n" + e.Message);
Console.ReadLine();
}
}

最佳答案

您的结果中有一个状态代码。

responseTask.Result.StatusCode

甚至更好

    var response = await client.SendAsync(request);
var statusCode = response.StatusCode;

关于C# - 如何从 http 请求中获取 HTTP 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59284261/

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