0

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}}
Bokambo
  • 4,204
  • 27
  • 79
  • 130
  • You're posting your data via `solrClient`, your HttpClient `wc` isn't even used. Also you're setting the Accept header, not the `Content-Type` header as in your WebClient example. – Tobias Tengler Jul 08 '19 at 16:56
  • In addition, you are not receiving any errors because you are not validating the response from the client. `PostAsync` returns a `HttpResponseMessage` object that includes the actual response, as well as the http status code returned from the service. – ESG Jul 08 '19 at 16:58
  • Updated. It gives me error as "missing content type". How i can correctly pass the content type ? – Bokambo Jul 08 '19 at 18:39

1 Answers1

0

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});
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31
  • It gives me error as "missing content type". How i can correctly pass the content type ? – Bokambo Jul 08 '19 at 18:40
  • What content type?? no content type is needed. try and show the api method, so we know what you are trying to call?. and also post the error message you are getting – Alen.Toma Jul 08 '19 at 20:31
  • { "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}} – Bokambo Jul 08 '19 at 20:38
  • 1
    Ok its unsupported contentType error. your server dose not accept the default contenttype. So you have to specify it. i though you are using mvc as a server :). Try and specify a contentType. Read this to know how you can do it (https://stackoverflow.com/questions/10679214/how-do-you-set-the-content-type-header-for-an-httpclient-request) – Alen.Toma Jul 08 '19 at 20:46
  • I tried passing ContentType but it says Missing Content Type see my above code in the post. – Bokambo Jul 08 '19 at 20:55
  • Well i got nothing, see this solution here if it help you `https://stackoverflow.com/questions/5727088/org-apache-solr-common-solrexception-missing-content-stream` – Alen.Toma Jul 08 '19 at 21:12
  • Yes.Thanks. It helped me. (https://stackoverflow.com/questions/10679214/how-do-you-set-the-content-type-header-for-an-httpclient-request) – Bokambo Jul 09 '19 at 16:04