我有以下代码,可以正常工作(给定正确的URL等)作为POST请求。似乎我在读取状态代码时遇到问题(我收到了成功的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();
}
}
答案 0 :(得分:6)
结果中有一个状态码。
responseTask.Result.StatusCode
甚至更好
var response = await client.SendAsync(request);
var statusCode = response.StatusCode;
答案 1 :(得分:1)
如果您已经在ContinueWith
函数内部,则可以避免使用async
,因为您可以使用(更简洁的)await
关键字。
如果您通过await
进行SendAsync
调用,则会得到一个HttpResponseMessage
对象,您可以从以下位置获取状态代码:
另外,将IDisposable
对象包装在using()
块中(HttpClient
除外-应该是static
单例或更优,请使用{{1} })。
请勿将IHttpClientFactory
用于特定于请求的标头,而应使用HttpClient.DefaultRequestHeaders
。
HttpRequestMessage.Headers
头将由Connection: Keep-alive
自动为您发送。HttpClientHandler
吗?如果您使用的是HTTPS,那么几乎可以保证不会有任何引起问题的代理缓存-并且Cache-control: no-cache
也不会使用Windows Internet缓存。HttpClient
,因为它会添加前导字节顺序标记。请改用私有Encoding.UTF8
实例。.ConfigureAwait(false)
,其中每个UTF8Encoding
上的代码都不能在线程敏感的上下文中运行(例如WinForms和WPF)。await
答案 2 :(得分:1)
您可以简单地检查响应的StatusCode属性:
static async void dotest(string url)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode.ToString());
}
else
{
// problems handling here
Console.WriteLine(
"Error occurred, the status code is: {0}",
response.StatusCode
);
}
}
}
答案 3 :(得分:0)
@AthanasiosKataras对于返回状态代码本身是正确的,但是如果您还想返回状态代码值(即200、404),则是正确的。您可以执行以下操作:
var response = await client.SendAsync(request);
int statusCode = (int)response.StatusCode
以上将为您提供int 200。
编辑:
没有理由不能执行以下操作吗?
using (HttpResponseMessage response = await client.SendAsync(request))
{
// code
int code = (int)response.StatusCode;
}