我正在尝试使用C#HttpClient创建一个将一些数据发布到API端点的服务。代码如下。
public class HttpClientService : IHttpClientService
{
static HttpClient client = new HttpClient();
public HttpClientService()
{
client.BaseAddress = new Uri("http://xx.xx.xx.xx/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<Uri> MakeLogEntry(CnsLog log)
{
HttpResponseMessage response = await client.PostAsJsonAsync("api/logs", log);
return response.Headers.Location;
}
}
问题是终点返回错误411 Length Required。我发现这是因为我的请求没有内容长度标头集,我在使用Fiddler检查请求时发现这是真的。
我试图在构造函数中设置客户端上的内容长度标头,但之后代码不编译。我被困住了,不胜感激任何帮助。谢谢
您不希望在客户端上设置Content-Length
标头,尤其是因为它是静态实例。您想根据个别请求进行设置。
PostAsJsonAsync
是一个很好的快捷方式,从poco构建HttpContent
,从该内容构建HttpRequestMessage
,并发送POST请求。方便,但所有抽象都没有给你机会设置请求级标头。所以,你需要做更多的工作来构建/发送请求:
var json = JsonConvert.SerializeObject(log);
var content = new StringContent(json, Encoding.UTF8, "application/json");
content.Headers.ContentLength = json.Length;
var response = await client.PostAsync("api/logs", content);
或者你可以使用HttpWebRequest
。
byte[] postBytes = Encoding.ASCII.GetBytes(log);
request.ContentLength = postBytes.Length;
HttpWebRequest的示例如下:
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes(serializedObject); // a json object, or xml, whatever...
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
request.Expect = "application/json";
request.GetRequestStream().Write(data, 0, data.Length);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;