使用HttpClient和Windows-1252编码的url

时间:2015-01-02 13:16:16

标签: c# .net xamarin httpclient

我尝试使用System.Net.HttpClient与非常简单的Web API进行通信。此API客户端具有搜索功能,我可以通过其名称搜索用户。问题是API在URL中使用Windows 1252编码,当我尝试使用带有HttpClient的Windows 1252编码URL时,HttpClient在发出请求之前使用utf-8对url进行编码。

string name = "Arnar Aðalsteinsson"; // My name, note the 'ð' character
string encodedName = HttpUtility.UrlEncode(name, Encoding.GetEncoding(1252));
string url = string.Format("http://website.com/find?name={0}", encodedName);

// url = http://website.com/find?name=Arnar+A%f0dalsteinsson

string result = httpClient.GetStringAsync(url)
// result = "Name A%f0dalsteinsson is unknown", actual output from API service
// httpClient encodes the previously encoded parameter to A%25f0dalsteinsson

当我在浏览器中使用编码地址(http://website.com/find?name=Arnar+A%f0dalsteinsson)时,它可以正常工作。

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:0)

我在尝试重现这个问题时找不到问题,它在我这边工作正常,尝试使用fiddler查看您的请求结果,可能是您服务器端的问题。

这是我的代码:

string name = "Arnar Aðalsteinsson"; 
        string encodedName = HttpUtility.UrlEncode(name, Encoding.GetEncoding(1252));
        string url = string.Format("http://website.com/find?name={0}", encodedName);

        HttpClient httpClient = new HttpClient();
        try
        {
            **string result = httpClient.GetStringAsync(url).Result;**

        }
        catch (System.AggregateException ex) {

            Debug.WriteLine(ex.Message);


        }

结果:website.com/find?name = Arnar + A%f0alsteinsson

相关问题