102425074
102425074

Reputation: 811

How can I send a POST request to a remote server?

My website needs to post requests to a remote server to use its API.

I found a way in google by using HttpClient, just like this:

public async Task<string> HttpPostAsync(string uri, string url, List<KeyValuePair<string, string>> formData = null, string charset = "UTF-8", string mediaType = "application/x-www-form-urlencoded")
    {

      string tokenUri = url;
      var client = new HttpClient();
      client.BaseAddress = new Uri(uri);
      HttpContent content = new FormUrlEncodedContent(formData);
      content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
      content.Headers.ContentType.CharSet = charset;
      for (int i = 0; i < formData.Count; i++)
      {
        content.Headers.Add(formData[i].Key, formData[i].Value);
      }

      HttpResponseMessage resp = await client.PostAsync(tokenUri, content);
      resp.EnsureSuccessStatusCode();
      string token = await resp.Content.ReadAsStringAsync();
      return token;
    }

This way works, but the example is from 2017 when .NET Core 1.1 was just published.

Now .NET Core 3.0 is available and I wonder if there is any other better way to achieve this?

Upvotes: 1

Views: 1469

Answers (1)

Nate Barbettini
Nate Barbettini

Reputation: 53610

HttpClient is still the simplest/best way to directly make HTTP calls in .NET. For a method that always posts form content, you can simplify it a bit (no need to specify the media type, charset, etc. every time):

public static async Task<string> Post(string url, IEnumerable<KeyValuePair<string, string>> formData)
{
    var client = new HttpClient();
    var formContent = new FormUrlEncodedContent(formData);
    var response = await client.PostAsync(url, formContent);

    response.EnsureSuccessStatusCode();
    return await response.Content.ReadAsStringAsync();
}

var stringResponse = await Post("https://so57994582.free.beeceptor.com",
    new Dictionary<string, string>() { { "hello", "world" } });

Upvotes: 1

Related Questions