簡體   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