Search code examples
.nethttpprotocolswebclienthttp-status-code-400

.NET WebClient 400 error


I am doing a HTTP "PUT" using the WebClient class for a JSON string to an Elastic Search. This code works in 95% of the cases but fails for the rest. The error I get is 400 bad protocol in my code. When I post the same JSON using jQuery AJAX or a Chrome extension called Postman, it works flawlessly. I am not sure how to get around this error. My code is below -

string json = "{some json}";
WebClient client = new WebClient();
client.Headers["Content-Type"] = "application/json;charset=UTF-8";    

try
{
     json = client.UploadString(URL, "PUT", json);
}
catch (WebException ex)
{
     //catch exception
}

Solution

  • Elastic Search expects some headers which WebClient does not pass. I used HttpWebRequest class and it worked fine without any errors since.