繁体   English   中英

将 Httpwebrequest 转换为 Httpclient

[英]Convert Httpwebrequest to Httpclient

这是获取令牌的完整代码。 我想把它翻译成Httpclient。 希望有人能帮助我。 我想从 httpwebrequest 切换到 httpclient 非常感谢你帮助我。

  public static async Task<TokenInfo> GetToken(string userName, string password)
    {
        string text = "https://api.site.io/v4/sessions.json?app=100005a&t=1569053071";
    
        string postDataStr = string.Concat(new string[]
        {
            "{\"password\": \"", password,
            "\", \"login_id\": \"", userName,"\"}"
        });
        
        var token_info = JObject.Parse(await Post(text, postDataStr));
        var token = token_info["token"].ToString();
    
        string user = token_info["user"]["name"].ToString();
        string country = token_info["user"]["country"].ToString();
    
        return new TokenInfo()
        {
            Token = token,
            Name = user,
            Country = country
        };
    }

private static HttpWebRequest httpWebRequest;
public static async Task<string> Post(string Url, string postDataStr)
{
    var uri = new Uri(Url);
    httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
    httpWebRequest.Method = "POST";
    httpWebRequest.ContentType = "text/plain";
    httpWebRequest.KeepAlive = false;
    httpWebRequest.ContentLength = (long)Encoding.UTF8.GetByteCount(postDataStr);
    using (var writer = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.GetEncoding("gb2312")))
    {
        await writer.WriteAsync(postDataStr);
    }
    using (var response = (await httpWebRequest.GetResponseAsync()).GetResponseStream())
    {
        using (var reader = new StreamReader(response, Encoding.GetEncoding("utf-8")))
        {
            var result = await reader.ReadToEndAsync();
            Console.WriteLine(result);
            return result;
        }
    }
}
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
                           SecurityProtocolType.Tls11 |
                           SecurityProtocolType.Tls12;
 HttpClient httpClient = new HttpClient();

    var request = new HttpRequestMessage(HttpMethod.Post, Url)
    {
        Content = new StringContent(postDataStr, Encoding.UTF8, "text/plain")
    };

   
    using (var response = await httpClient.SendAsync(request))
    {
        response.EnsureSuccessStatusCode();
        var body = await response.Content.ReadAsStringAsync();
        
    }

这是一个发布请求的示例,例如您使用HttpClient发布的示例

    public static async Task<string> Post(string url, Dictionary<string,string> postParameters)
    {
        using (HttpClient client = new HttpClient())
        {

            HttpContent postData = new FormUrlEncodedContent(postParameters);

            HttpResponseMessage response = await client.PostAsync(url, postData);

            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();

                return content;
            }
            else
            {
                //Do something when request fails
                return string.Empty;
            }
        }
    }

我添加了一个Dictionary<string, string>而不是您的方法中的 postDataStr 参数

因此,假设您想将一些数据发布到需要一些数据(如用户名和密码)的端点,那么您可以这样做:

    Dictionary<string, string> postData = new Dictionary<string, string>();
    postData.Add("Username", "MyUsername");
    postData.Add("Password", "MyPassword");

    await Post("MyUrl", postData);

如果您更喜欢发送纯字符串而不是使用 Dictionary 解决方案,您可以这样做:

    public static async Task<string> Post(string url, string postDataStr)
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Content-Type", "text/plain");

            HttpContent postData = new StringContent(postDataStr);

            HttpResponseMessage response = await client.PostAsync(url, postData);

            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();

                return content;
            }
            else
            {
                //Do something when request fails
                return string.Empty;
            }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM