zackmark15
zackmark15

Reputation: 727

Convert Httpwebrequest to Httpclient

Here's the the whole code for getting token. I wanna translate this to Httpclient. hope that someone can help me. I want to switch from httpwebrequest to httpclient Thank you so much for helping me out.

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

Upvotes: 0

Views: 2367

Answers (2)

Martin C
Martin C

Reputation: 140

Here is an example of doing a post request like the example you have posted with 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;
            }
        }
    }

Instead of your postDataStr parameter in your method i have added a Dictionary<string, string>

So lets say you want to post some data to a endpoint that expects some data like Username and Password, then you can do it this way:

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

    await Post("MyUrl", postData);

If you prefer to send a plain string instead of using the Dictionary solution you can do it this way:

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

Upvotes: 1

Ansil F
Ansil F

Reputation: 284

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

Upvotes: 2

Related Questions