【问题标题】:Replacing WebClient with HttpClient用 HttpClient 替换 WebClient
【发布时间】: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 发布您的数据,您的HttpClient wc 甚至没有被使用。此外,您正在设置 Accept 标头,而不是 WebClient 示例中的 Content-Type 标头。
  • 此外,您没有收到任何错误,因为您没有验证来自客户端的响应。 PostAsync 返回一个 HttpResponseMessage 对象,其中包括实际响应以及从服务返回的 http 状态代码。
  • 已更新。它给了我“缺少内容类型”的错误。我如何正确传递内容类型?

标签: c# httpclient webclient


【解决方案1】:

你的方法是post还是get??

无论如何,这里有一个更好的例子来说明如何构建 POST 和 GET

     private static readonly HttpClient client = new HttpClient();
     // HttpGet
     public static async Task<object> GetAsync(this string url, object parameter = null, Type castToType = null)
        {
            if (parameter is IDictionary)
            {
                if (parameter != null)
                {
                    url += "?" + string.Join("&", (parameter as Dictionary<string, object>).Select(x => $"{x.Key}={x.Value ?? ""}"));
                }
            }
            else
            {
                var props = parameter?.GetType().GetProperties();
                if (props != null)
                    url += "?" + string.Join("&", props.Select(x => $"{x.Name}={x.GetValue(parameter)}"));
            }

            var responseString = await client.GetStringAsync(new Uri(url));
            if (castToType != null)
            {
                if (!string.IsNullOrEmpty(responseString))
                    return JsonConvert.DeserializeObject(responseString, castToType);
            }

            return null;
        }
   // HTTPPost
   public static async Task<object> PostAsync(this string url, object parameter, Type castToType = null)
    {
        if (parameter == null)
            throw new Exception("POST operation need a parameters");
        var values = new Dictionary<string, string>();
        if (parameter is Dictionary<string, object>)
            values = (parameter as Dictionary<string, object>).ToDictionary(x => x.Key, x => x.Value?.ToString());
        else
        {
            values = parameter.GetType().GetProperties().ToDictionary(x => x.Name, x => x.GetValue(parameter)?.ToString());
        }

        var content = new FormUrlEncodedContent(values);
        var response = await client.PostAsync(url, content);
        var contents = await response.Content.ReadAsStringAsync();
        if (castToType != null && !string.IsNullOrEmpty(contents))
            return JsonConvert.DeserializeObject(contents, castToType);
        return null;
    }

现在您只需发送数据

     // if your method has return data you could set castToType to 
    // convert the return data to your desire output
    await PostAsync(solrCoreConnection + "/update",new {commit= true, Id=5});

【讨论】:

  • 它给了我“缺少内容类型”的错误。我如何正确传递内容类型?
  • 什么内容类型??不需要内容类型。尝试显示 api 方法,以便我们知道您要调用什么?并发布您收到的错误消息
  • { "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}}
  • 好吧,它不支持的 contentType 错误。您的服务器不接受默认的内容类型。所以你必须指定它。我虽然你使用 mvc 作为服务器:)。尝试并指定一个 contentType。阅读本文以了解如何做到这一点 (stackoverflow.com/questions/10679214/…)
  • 我尝试传递 ContentType 但它说 Missing Content Type 请在帖子中查看我上面的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多