0

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;
        }
    }
}
zackmark15
  • 657
  • 6
  • 12

2 Answers2

2
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();
        
    }
Ansil F
  • 284
  • 1
  • 8
  • Wow gonna try this now – zackmark15 Aug 12 '20 at 12:11
  • I got this error from sendasync part Object reference not set to an instance of an object.' – zackmark15 Aug 12 '20 at 12:13
  • I'm getting now "Response status code does not indicate 404 not Found" Is it possilbe that I got blocked from sending request? earlier in the morning my code is working but when I tried again I always getting error – zackmark15 Aug 12 '20 at 12:43
  • This error means your httpclient worked but it cannot find the resource in the url. Check whether url is correct or not. – Ansil F Aug 12 '20 at 12:46
1

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;
            }
        }
    }
Martin C
  • 120
  • 1
  • 8