用HttpClient替换WebClient

时间:2019-07-08 16:53:25

标签: c# httpclient webclient

我正在尝试用HttpClient替换Webclient,以实现项目中的当前功能。 HttpClient不会给出任何错误,但是不会从Solr中删除索引。我想念什么? 它给我:缺少内容类型 我如何正确传递内容类型?

WebClient:

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}}

1 个答案:

答案 0 :(得分:0)

您的方法是发布还是获取?

无论如何,这是如何构建POST和GET的一个更好的例子

OVRPRTF    FILE(PRNTFILE) SCHEDULE(*FILEEND) SHARE(*YES)

现在您只需发送数据

     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;
    }