我正在尝试使用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所需长度。我发现这是因为我的请求没有设置content-length标头,当我使用Fiddler检查该请求时发现这是正确的。
我尝试在构造函数中的客户端上设置内容长度标头,但此后代码无法编译。我被困住了,不胜感激。谢谢
答案 0 :(得分:2)
您不想在客户端上设置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);
答案 1 :(得分:0)
您也可以使用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;