如何设置Accept和Accept-Language标题字段?

时间:2011-06-03 07:57:19

标签: c# httpwebrequest

我可以设置Request.Content-Type = ...,Request.Content-Length = ...

如何设置接受和接受语言?

我想上传文件(RFC 1867)并需要创建一个这样的请求:

POST /test-upload.php.xml HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 5.2; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: tr-tr,tr;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-9,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------21724139663430
Content-Length: 56048

5 个答案:

答案 0 :(得分:33)

看看Accept property

HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create(myUri);
myHttpWebRequest.Accept="image/*";    
HttpWebResponse myHttpWebResponse=
         (HttpWebResponse)myHttpWebRequest.GetResponse();

This MSDN article显示了如何向您的请求添加自定义标头:

//Get the headers associated with the request.
WebHeaderCollection myWebHeaderCollection = myHttpWebRequest.Headers;    

//Add the Accept-Language header (for Danish) in the request.
myWebHeaderCollection.Add("Accept-Language:da");

//Include English in the Accept-Langauge header. 
myWebHeaderCollection.Add("Accept-Language","en;q=0.8");

答案 1 :(得分:2)

您需要确保将请求类型转换为(HttpWebRequest),其中accept header属性可用。

在旧的WebRequest类中,无法访问Accept标头。

答案 2 :(得分:2)

如果要设置Accept类型和内容类型,只需将webrequest转换为HttpwebRequest

var webreq= (HttpWebRequest)WebRequest.Create(requestUri);
webreq.Method = "POST";
webreq.Accept = "application/json";
webreq.ContentType = "application/json";

答案 3 :(得分:1)

我必须在几次恼人的尝试后确认使用

的标题

myWebHeaderCollection.Add("foo","bar");解决方案完美无缺。

如果你想设置语言。

myWebHeaderCollection.Add("AcceptCharset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
myWebHeaderCollection.Add("TransferEncoding", "gzip,deflate");

但是不设置值。鉴于第一个有效,这似乎是一个合乎逻辑的结论。

答案 4 :(得分:0)

如果您使用的是HttpRequestMessage,请使用Headers.Add方法设置标头。在你的情况下:

request.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
相关问题