c# net451 写一个返回HttpResponseMessage的方法方法内容有HttpClient同步请求post的例子需要带名为Authorization的header并且
传入一个字符串类型的token作为参数:
public HttpResponseMessage PostWithAuthorizationHeader(string url, string token, HttpContent content)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = client.PostAsync(url, content).Result;
return response;
}
}
调用示例:
var content = new StringContent("{\"name\":\"John\", \"age\":30}", Encoding.UTF8, "application/json");
var response = PostWithAuthorizationHeader("https://example.com/api/person", "mytoken123", content);
注意:这是一个同步的请求方法,如果需要异步请求可以使用client.PostAsync()方法,并将方法声明为async和返回类型改为Task<HttpResponseMessage>。
原文地址: https://www.cveoy.top/t/topic/1zl 著作权归作者所有。请勿转载和采集!