Search code examples
c#httpclientwebclient

Replacing WebClient with HttpClient


I am trying to replace Webclient with HttpClient for my current functionality in my project. HttpClient does not give any error but does not delete index from Solr. What i am missing ? It gives me : Missing content type How i can correctly pass the content type ?

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: (no errors, but doesn't delete the index)

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;

}

It gives me : Missing content type How i can correctly pass the content type ?

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

Solution

  • Well Is your method post or get??

    Well anyway here is a better exmaple of how you could build POST and 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;
        }
    

    And now you simply send your data

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