将 WebClient 转换为 HttpClient

Convert WebClient to HttpClient

我正在尝试将我曾经在 Win7 项目上使用的 WebClient 转换为 HttpClient,以便在我的 Win8.1 系统上使用它。

文客户端:

public static void PastebinSharp(string Username, string Password)
        {
            NameValueCollection IQuery = new NameValueCollection();

            IQuery.Add("api_dev_key", IDevKey);
            IQuery.Add("api_user_name", Username);
            IQuery.Add("api_user_password", Password);

            using (WebClient wc = new WebClient())
            {
                byte[] respBytes = wc.UploadValues(ILoginURL, IQuery);
                string resp = Encoding.UTF8.GetString(respBytes);

                if (resp.Contains("Bad API request"))
                {
                    throw new WebException("Bad Request", WebExceptionStatus.SendFailure);
                }
                Console.WriteLine(resp);
                //IUserKey = resp;
            }
        }

这是我第一次使用 HttpClient

public static async Task<string> PastebinSharp(string Username, string Password)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("api_dev_key", GlobalVars.IDevKey);
                client.DefaultRequestHeaders.Add("api_user_name", Username);
                client.DefaultRequestHeaders.Add("api_user_password", Password);

                using (HttpResponseMessage response = await client.GetAsync(GlobalVars.IPostURL))
                {
                    using (HttpContent content = response.Content)
                    {
                        string result = await content.ReadAsStringAsync();
                        Debug.WriteLine(result);
                        return result;
                    }
                }
            }
        }

我的HttpRequestreturnsBad API request, invalid api option而我的WebClientreturns回复成功。

应该怎么做?

我当然知道我在添加 headers 而不是查询,但我不知道如何添加查询...

UploadValues 的 msdn 页面说 WebClient 使用 application/x-www-form-urlencoded Content-type 在 POST 请求中发送数据。所以你 must/can 使用 FormUrlEncodedContent http 内容。

public static async Task<string> PastebinSharpAsync(string Username, string Password)
{
    using (HttpClient client = new HttpClient())
    {
        var postParams = new Dictionary<string, string>();

        postParams.Add("api_dev_key", IDevKey);
        postParams.Add("api_user_name", Username);
        postParams.Add("api_user_password", Password);

        using(var postContent = new FormUrlEncodedContent(postParams))
        using (HttpResponseMessage response = await client.PostAsync(ILoginURL, postContent))
        {
            response.EnsureSuccessStatusCode(); // Throw if httpcode is an error
            using (HttpContent content = response.Content)
            {
                string result = await content.ReadAsStringAsync();
                Debug.WriteLine(result);
                return result;
            }
        }
    }
}