How can one use HttpClient and set the method dynamically without having to do something like:
public async Task<HttpResponseMessage> DoRequest(string url, HttpContent content, string method)
{
HttpResponseMessage response;
using (var client = new HttpClient())
{
switch (method.ToUpper())
{
case "POST":
response = await client.PostAsync(url, content);
break;
case "GET":
response = await client.GetAsync(url);
break;
default:
response = null;
// Unsupported method exception etc.
break;
}
}
return response;
}
At the moment it looks like you would have to use:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
but there is no ready constructor that converts HTTP method string to HttpMethod
Well that's not true any longer...1
public HttpMethod(string method);
Can be used like this:
var httpMethod = new HttpMethod(method.ToUpper());
Here is working code.
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
namespace MyNamespace.HttpClient
{
public static class HttpClient
{
private static readonly System.Net.Http.HttpClient NetHttpClient = new System.Net.Http.HttpClient();
static HttpClient()
{}
public static async System.Threading.Tasks.Task<string> ExecuteMethod(string targetAbsoluteUrl, string methodName, List<KeyValuePair<string, string>> headers = null, string content = null, string contentType = null)
{
var httpMethod = new HttpMethod(methodName.ToUpper());
var requestMessage = new HttpRequestMessage(httpMethod, targetAbsoluteUrl);
if (!string.IsNullOrWhiteSpace(content) || !string.IsNullOrWhiteSpace(contentType))
{
var contentBytes = Encoding.UTF8.GetBytes(content);
requestMessage.Content = new ByteArrayContent(contentBytes);
headers = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Content-type", contentType)
};
}
headers?.ForEach(kvp => { requestMessage.Headers.Add(kvp.Key, kvp.Value); });
var response = await NetHttpClient.SendAsync(requestMessage);
return await response.Content.ReadAsStringAsync();
}
}
}