【发布时间】:2019-07-08 16:53:25
【问题描述】:
我正在尝试用 HttpClient 替换 Webclient,以实现我项目中的当前功能。 HttpClient 不会给出任何错误,但不会从 Solr 中删除索引。我错过了什么? 它给了我:缺少内容类型 如何正确传递内容类型?
网络客户端:
public static byte[] deleteIndex(string id)
{
System.Uri uri = new System.Uri(solrCoreConnection + "/update?commit=true");
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "text/xml";
return wc.UploadData(uri, "POST", Encoding.ASCII.GetBytes("<delete><id>" + id + "</id></delete>"));
}
}
HttpClient:(没有错误,但不会删除索引)
public static async Task<HttpResponseMessage> deleteIndex(string id)
{
System.Uri uri = new System.Uri(solrCoreConnection + "/update?commit=true");
ResettableLazy<HttpClient> solrClient = new ResettableLazy<HttpClient>(SolrInstanceFactory);
solrClient.Value.DefaultRequestHeaders.Add("ContentType", "text/xml");
byte[] bDelete = Encoding.ASCII.GetBytes("<delete><id>" + id + "</id></delete>");
ByteArrayContent byteContent = new ByteArrayContent(bDelete);
HttpResponseMessage response = await solrClient.Value.PostAsync(uri.OriginalString, byteContent);
var contents = await response.Content.ReadAsStringAsync();
return response;
}
它给了我:缺少内容类型 如何正确传递内容类型?
{
"responseHeader":{
"status":415,
"QTime":1},
"error":{
"metadata":[
"error-class","org.apache.solr.common.SolrException",
"root-error-class","org.apache.solr.common.SolrException"],
"msg":"Missing ContentType",
"code":415}}
【问题讨论】:
-
您正在通过
solrClient发布您的数据,您的HttpClientwc甚至没有被使用。此外,您正在设置 Accept 标头,而不是 WebClient 示例中的Content-Type标头。 -
此外,您没有收到任何错误,因为您没有验证来自客户端的响应。
PostAsync返回一个HttpResponseMessage对象,其中包括实际响应以及从服务返回的 http 状态代码。 -
已更新。它给了我“缺少内容类型”的错误。我如何正确传递内容类型?
标签: c# httpclient webclient