将WebClient转换为HttpClient

时间:2017-02-04 22:08:17

标签: c# http request httpclient webclient

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

WenClient:

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;
                    }
                }
            }
        }

当我的HttpRequest返回成功回复时,我的Bad API request, invalid api option会返回WebClient

应该怎么做?

我理解当然我正在添加标题而不是查询,但我不知道如何添加查询......

1 个答案:

答案 0 :(得分:4)

UploadValues的msdn页面表示WebClient在具有application/x-www-form-urlencoded内容类型的POST请求中发送数据。因此,您必须/可以使用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;
            }
        }
    }
}