C# HttpClient FormUrlEncodedContent 编码 (VS 2012)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12390511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# HttpClient FormUrlEncodedContent Encoding (VS 2012)
提问by Todd Booth
I'm using the HttpClient. I'm posting with web form parameters. One of the values (not name) is a foreign Swedish character ? , #246; ? ASCII: Latin Small Letter O Umlaut
我正在使用 HttpClient。我正在发布带有网络表单参数的帖子。其中一个值(不是名称)是外来瑞典字符?, #246; ? ASCII:拉丁小写字母 O 元音变音
Manually, IE, Firefox and Chrome all convert this character to S%F6k and everything works fine. However VS 2012 C# release converts it (via FormUrlEncodedContent(dict)) to %C3%B6
手动,IE、Firefox 和 Chrome 都将此字符转换为 S%F6k,一切正常。然而,VS 2012 C# 版本将它(通过 FormUrlEncodedContent(dict))转换为 %C3%B6
Is there a way to tell VS 2012 to convert it, to the friendly S%F6k (and still use HttpClient)?
有没有办法告诉 VS 2012 将它转换为友好的 S%F6k(并且仍然使用 HttpClient)?
I've attached most of the code, which may help others (cookies, proxy, etc...)
我附上了大部分代码,这可能对其他人有帮助(cookies、代理等...)
// Create Handler
var handler = new HttpClientHandler();
// Cookies
var cc = new CookieContainer();
handler.CookieContainer = cc;
// Proxy - for fiddler
WebProxy proxy = new WebProxy();
proxy.Address = new Uri("http://localhost:8888");
handler.Proxy = proxy;
// Create the client
var client = new HttpClient(handler);
var request4 = new HttpRequestMessage();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "text/html, application/xhtml+xml, */*");
client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
client.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.8,sv-SE;q=0.5,sv;q=0.3");
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
// Form Data
var dict4 = new Dictionary<string, string>
{
{ "page", "kantlista" },
{ "kod", "A0004n" },
{ "termin", "H12" },
{ "anmkod", "17113" },
{ "urval", "ant" },
{ "listVal", "namn" },
{ "method", "S?k" } // S%F6k
}; // dict
request4.Content = new FormUrlEncodedContent(dict4);
var value4 = new FormUrlEncodedContent(dict4);
string uri4 = "https://www.ltu.se/ideal/ListaKursant.do";
var response4 = await client.PostAsync(uri4, value4);
response4.Headers.Add("Cache-Control", "no-cache")
response4.EnsureSuccessStatusCode();
string responseBody4 = await response4.Content.ReadAsStringAsync();
采纳答案by Tyler Tsai
FormUrlEncodedContentclass encode form data in utf8 encoding.
try ByteArrayContentclass and HttpUtility.UrlEncode(String, Encoding)to encode.
FormUrlEncodedContent类以 utf8 编码对表单数据进行编码。
尝试ByteArrayContent类并HttpUtility.UrlEncode(String, Encoding)进行编码。

