Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebClient set headers

How I can set a header in the webClient class? I tried:

client.Headers["Content-Type"] = "image/jpeg"; 

that throws a WebException

My code:

WebClient client = new WebClient(); client.Headers.Set("Content-Type", "image/png"); client.Headers.Set("Content-Length", length); client.Headers.Add("Slug", name); NameValueCollection nvc = new NameValueCollection(); nvc.Add("file", FileContents);  Byte[] data = client.UploadValues(url, nvc); string res = Encoding.ASCII.GetString(data); Response.Write(res); 
like image 296
The Mask Avatar asked Jul 03 '11 02:07

The Mask


People also ask

What is a header in WebClient?

The Headers property contains a WebHeaderCollection instance containing protocol headers that the WebClient sends with the request. Some common headers are considered restricted and are protected by the system and cannot be set or changed in a WebHeaderCollection object.

What is difference between HttpClient and WebClient?

In a nutshell, WebRequest—in its HTTP-specific implementation, HttpWebRequest—represents the original way to consume HTTP requests in . NET Framework. WebClient provides a simple but limited wrapper around HttpWebRequest. And HttpClient is the new and improved way of doing HTTP requests and posts, having arrived with .

What is WebClient spring boot?

Simply put, WebClient is an interface representing the main entry point for performing web requests. It was created as part of the Spring Web Reactive module and will be replacing the classic RestTemplate in these scenarios.


2 Answers

If the header already exists:

client.Headers.Set("Content-Type", "image/jpeg"); 

if its a new header:

client.Headers.Add("Content-Type", "image/jpeg"); 

Also, there is a chance that you are getting an error because you are trying to set the headers too late. Post your exception so we can let you know.

Update

Looks like there are some weird restrictions on the "Content-Type" header with the WebClient class. Look in to using the client.Download methods (DownloadData, DownloadFile, etc...)

See if using the "UploadFile" method on webclient works rather than doing it manually. It returns the respose body byte[].

If you continue to have issues with the WebClient, try justing using a plain old HttpRequest/HttpWebRequest.

like image 126
jdc0589 Avatar answered Sep 17 '22 13:09

jdc0589


It seems you can not set Content-type with WebClient.UploadValues method. You could set Content-type with WebClient.UploadData method

Use something like,

Client.Headers["Content-Type"] = "application/json"; Client.UploadData("http://www.imageshack.us/upload_api.php", "POST", Encoding.Default.GetBytes("{\"Data\": \"Test\"}")); 
like image 25
SajithK Avatar answered Sep 19 '22 13:09

SajithK