我正在使用HttpClient。我发布了web表单参数。其中一个值(不是名字)是外国瑞典人字符ö,#246; öASCII:Latin Small Letter O Umlaut
手动,IE,Firefox和Chrome都将此角色转换为S%F6k,一切正常。然而,VS 2012 C#版本将其(通过FormUrlEncodedContent(dict))转换为%C3%B6
有没有办法告诉VS 2012将其转换为友好的S%F6k(仍然使用HttpClient)?
我附上了大部分代码,可能会帮助其他代码(Cookie,代理等等)
// 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();
答案 0 :(得分:8)
FormUrlEncodedContent
类以utf8编码对表单数据进行编码
尝试ByteArrayContent
类和HttpUtility.UrlEncode(String, Encoding)
进行编码。
答案 1 :(得分:0)
只需完成@TylerTsai的答案
替换
var dict = new Dictionary<string, string>();
dict.Add("param1", value1);
dict.Add("param1", value2);
var response = await httpClient.PostAsync(endpoint, new FormUrlEncodedContent(dict));
使用
string postData = HttpUtility.UrlEncode(
$"param1={value1}¶m2={value2}",Encoding.GetEncoding(myEncoding));
byte[] data = System.Text.Encoding.GetEncoding(myEncoding).GetBytes(postData);
ByteArrayContent content = new ByteArrayContent(data);
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var response = await httpClient.PostAsync(endpoint, content);