如何防止查询字符串httpclient的双重编码?

时间:2018-05-11 11:23:33

标签: c# encoding httpclient unicode-string

我的查询字符串包含unicode字符,例如。 “http://api.test.com?q=Túls Engeniería”。

我在get请求中发送此查询字符串,BuildUrl方法返回编码字符串 - httpclient.GetAsync("http://api.test.com?q=T%u00fals+Engenier%u00eda"),但在我在fiddler查询中看到的请求中另外编码 - “http://api.test.com?q=T%25u00fals+Engenier%25u00eda”,如何防止这种双重编码?

private async Task<string> MakeGetCall(string apiVersion, string url, string accessToken, NameValueCollection urlParameters = null)
{
    var client = GetHttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(Constants.AUTHORIZATION_HEADER_VALUE_CONST_PART, accessToken);

    var result = await client.GetAsync(BuildUrl(apiVersion + url, urlParameters));
    result.EnsureSuccess();

    return await result.Content.ReadAsStringAsync();
}

private string BuildUrl(string baseUrl, NameValueCollection urlParameters)
{
    string finalUrl = baseUrl;

     if (urlParameters != null)
     {
         var builder = new UriBuilder(string.Empty, baseUrl);
         var query = HttpUtility.ParseQueryString(builder.Query);

         query.Add(urlParameters);

         builder.Query = query.ToString();
         finalUrl = builder.ToString();
     }

     return finalUrl;
 }

0 个答案:

没有答案