Web客户端组头 [英] WebClient set headers

查看:128
本文介绍了Web客户端组头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置在 Web客户端类的标题?
我想:

  client.Headers [的Content-Type] =图像/ JPEG; 

这将引发引发WebException



我的代码:

  Web客户端的客户端=新的WebClient(); 
client.Headers.Set(内容类型,图像/ PNG);
client.Headers.Set(内容长度,长度);
client.Headers.Add(弹头,名);
的NameValueCollection雷士=新的NameValueCollection();
nvc.Add(文件,FileContents);

字节[]数据= client.UploadValues(URL,NVC);
串解析度= Encoding.ASCII.GetString(数据);
的Response.Write(RES);


解决方案

如果头已经存在:

  client.Headers.Set(内容类型,图像/ JPEG); 

如果它是一个新的头:

  client.Headers.Add(内容类型,图像/ JPEG); 



此外,还有一个机会,你得到,因为你想设置的标头太错误晚了。发表您的异常,所以我们可以让你知道。



更新



<罢工>看起来像有在内容类型标头WebClient类一些奇怪的限制。看看在使用client.Download方法(DownloadData,DownloadFile,等...)



如果使用一个UploadFile的方法对WebClient的工作,而见不是做手工。它返回respose身体的byte []。



如果你继续与WebClient的问题,请尝试justing使用普通的旧的HttpRequest / HttpWebRequest的。


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.

这篇关于Web客户端组头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆