@manhng

Welcome to my blog!

HttpClient

May 3, 2018 15:04

Constraining Concurrent Threads in C#

http://markheath.net/post/constraining-concurrent-threads-csharp

Custom Header to HttpClient Request

https://stackoverflow.com/questions/29801195/adding-headers-when-using-httpclient-getasync/38077835

https://stackoverflow.com/questions/35907642/custom-header-to-httpclient-request

client.DefaultRequestHeaders.Add("X-Version","1");

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your OAuth Token");

How to make HTTP POST web request (edit)

https://stackoverflow.com/questions/4015324/how-to-make-http-post-web-request

There are several ways to perform HTTP GET and POST requests:

Method A: HttpClient

Available in: .NET Framework 4.5+, .NET Standard 1.1+, .NET Core 1.0+

Currently the preferred approach. Asynchronous. Portable version for other platforms available via NuGet.

using System.Net.Http;

Setup

It is recommended to instantiate one HttpClient for your application's lifetime and share it.

private static readonly HttpClient client = new HttpClient();

POST

var values = new Dictionary<string, string>
{
   { "thing1", "hello" },
   { "thing2", "world" }
};

var content = new FormUrlEncodedContent(values);

var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

var responseString = await response.Content.ReadAsStringAsync();

GET

var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");

Method B: 3rd-Party Libraries

RestSharp

Tried and tested library for interacting with REST APIs. Portable. Available via NuGet.

Flurl.Http

Newer library sporting a fluent API and testing helpers. HttpClient under the hood. Portable. Available via NuGet.

using Flurl.Http;

POST

var responseString = await "http://www.example.com/recepticle.aspx"
    .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
    .ReceiveString();

GET

var responseString = await "http://www.example.com/recepticle.aspx"
    .GetStringAsync();

Method C: Legacy

Available in: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+

using System.Net;
using System.Text;  // for class Encoding
using System.IO;    // for StreamReader

POST

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

var postData = "thing1=hello";
    postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

GET

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Method D: WebClient (Also now legacy)

Available in: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 2.0+

using System.Net;
using System.Collections.Specialized;

POST

using (var client = new WebClient())
{
    var values = new NameValueCollection();
    values["thing1"] = "hello";
    values["thing2"] = "world";

    var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);

    var responseString = Encoding.Default.GetString(response);
}

GET

using (var client = new WebClient())
{
    var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}

Create New Asp.net Identity User using HttpClient from WinForms

November 10, 2017 09:18

Configure HttpClient

private static HttpClient httpClient = new HttpClient
{
BaseAddress = new Uri(ConfigManager.ConfigurationInstant.ApiBaseAuthUri)
};

private static HttpClient client = new HttpClient
{
BaseAddress = new Uri(ConfigManager.ConfigurationInstant.ApiBaseUri)
};

Create new user

private static async Task<ApiAsyncResult> CreateNewUser(string userName, string password, string confirmPassword)
{
var result = new ApiAsyncResult();

httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

try
{
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("email", userName),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("confirmPassword", confirmPassword)
});

using (HttpResponseMessage response = await httpClient.PostAsync("/Account/Register", formContent))
{
using (HttpContent content = response.Content)
{
string resultString = await content.ReadAsStringAsync();
string reasonPhrase = response.ReasonPhrase;
HttpResponseHeaders headers = response.Headers;
HttpStatusCode code = response.StatusCode;

result.Result = resultString;
result.ReasonPhrase = reasonPhrase;
result.Headers = headers;
result.Code = code;
}
}
}
catch (Exception ex)
{
result.ErrorMessage = ex.Message;
}

return result;
}

ApiAsyncResult.cs

public class ApiAsyncResult
{
public string Result { get; set; }
public string ReasonPhrase { get; set; }
public HttpResponseHeaders Headers { get; set; }
public HttpStatusCode Code { get; set; }
public string ErrorMessage { get; set; }
}

Categories

Recent posts