WebClient set headers - c#

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

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.

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\"}"));

Have you tried this syntax: client.Headers.Add("Content-Type", "image/jpeg");
What's your stack trace? At what point are you setting this? And what version of IIS/OS are you running under?

You cannot change the Content-Type if you use the UploadValues method, it must be application/x-www-form-urlencoded, see webclient source code

Related

Receive data from server using POST method and with a request body using WebClient in C#

I am trying to receive data back from the server using POST method and the request should have a body. I am using WebClient for this and trying to get the response back in string. I know we can use HttpClient to achieve this. But I want to use WebClient for this specific instance.
I went through this post and tried UploadString and the response gives me a 400 BAD Request.
using (var wc = new WebClient())
{
wc.Headers.Add("Accept: application/json");
wc.Headers.Add("User-Agent: xxxxxxx");
wc.Headers.Add($"Authorization: Bearer {creds.APIKey.Trim()}");
var jsonString = JsonConvert.SerializeObject(new UserRequestBody
{
group_id = userDetails.data.org_id
});
var response = wc.UploadString("https://api.xxxxx.yyy/v2/users", "POST", jsonString);
}
I tested the end point using Postman (with the request header having an api key and the request body in JSON) and it works fine.
I know I haven't formatted the request right. Can someone please help me.
Big Thanks to #Santiago Hernández. The issue was using wc.Headers.Add("Accept: application/json"); in the request header. Changing it to wc.Headers.Add("Content-Type: application/json"); returned a 200 Ok response. The code modification is as follows
using (var wc = new WebClient())
{
wc.Headers.Add("Content-Type: application/json");
wc.Headers.Add("User-Agent: xxxxxxx");
wc.Headers.Add($"Authorization: Bearer {creds.APIKey.Trim()}");
var jsonString = JsonConvert.SerializeObject(new UserRequestBody
{
group_id = userDetails.data.org_id
});
var response = wc.UploadString("https://api.xxxxx.yyy/v2/users", "POST", jsonString);
}
Accept tells the server the kind of response the client will accept and Content-type is about the payload/content of the current request or response. Do not use Content-type if the request doesn't have a payload/ body.
More information about this can be found here.

Using WebClient keeps changing json to text/plain for Content-Type

I'm using WebClient and I set the headers to JSON yet when I look at Fiddler, it shows text/plain. I do not understand why. I have to use WebClient (older app).
How do I enforce JSON to be sent in the request as Content-Type?
My relevant code:
var webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
webClient.Headers.Add("cache-control", "no-cache");
webClient.Headers.Add("Bearer", token);
//further down to the call...
var content = JsonConvert.SerializeObject(request).Replace(#"\\\", #"\");
var jsonResponse = webClient.UploadString($"https://{APIHost}{APIAddress}", content.ToString());

Post method for HTTP Handler

I have a handler. When I call it with URL that is to say GET method, it works because I get values with my below handler code.
var encodedUrl = HttpUtility.UrlEncode(context.Request.QueryString.ToString());
How can I get values when I use post method which is below from Handler side:
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["a"] = "a";
data["b"] = "b";
var response = wb.UploadValues("http://localhost:126/Web", "POST", data);
}
When you receive an http response you basically depend on the "Content Type". Depending on this type is that you read it.
Here is a reference on this topic:
http://msdn.microsoft.com/en-us/library/ms525208(v=vs.90).aspx
For instance if you decide to receive an "application/json" response type. You may be able to use this:
Using WebClient for JSON Serialization?
From I can see in your sample it looks like you are trying to implement an "application/x-www-form-urlencoded" and the post needs to be formatted accordingly. Here is a sample for that:
http://msdn.microsoft.com/en-us/library/system.net.webclient.headers(v=vs.110).aspx
How are parameters sent in an HTTP POST request?
But there are other options available. I hope this is the answer you were looking for.

No response when using WebClient.UploadFile

I'm uploading a file using the UploadFile method on the WebClient object. When the file is uploaded I would like to get a confirmation and according to MSDN (and also here on stackoverflow: Should I check the response of WebClient.UploadFile to know if the upload was successful?) I should be able to read the returned byte array but that is always empty.
Am I doing something the wrong way?
WebClient FtpClient = new WebClient();
FtpClient.Credentials = new NetworkCredential("test", "test");
byte[] responseArray = FtpClient.UploadFile("ftp://localhost/Sample.rpt", #"C:\Test\Sample.rpt");
string s = System.Text.Encoding.ASCII.GetString(responseArray);
Console.WriteLine(s); //Empty string
Or is it always successful if it doesn't return an exception?
Answer to myself: I couldn't make any sense of it so i switched to edt ftp (http://www.enterprisedt.com/) instead.

Invoking a URL - c#

I m trying to invoke a URL in C#, I am just interested in invoking, and dont care about response. When i have the following, does it mean that I m invoking the URL?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
You need to actually perform the request:
var request = (HttpWebRequest)WebRequest.Create(url);
request.GetResponse();
The call to GetResponse makes the outbound call to the server. You can discard the response if you don't care about it.
First) Create WebRequest to execute URL.
Second) Use WebResponse to get response.
Finally) Use StreamReader to decode response and convert it to normal string.
string url = "Your request url";
WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseText = reader.ReadToEnd();
You can use this:
string address = "http://www.yoursite.com/page.aspx";
using (WebClient client = new WebClient())
{
client.DownloadString(address);
}
No when you say request.GetResponse(); then you invoke it.
Probably not. See: http://www.codeproject.com/KB/webservices/HttpWebRequest_Response.aspx
You're allowed to set the Method, ContentType, etc., all which would have to be done before the request is actually sent. It looks like GetResponse() actually sends the request. You can simply ignore the return value.

Categories

Resources