Skip to content

Instantly share code, notes, and snippets.

@sakapon
Last active August 9, 2018 06:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sakapon/d0d1f80395740c2488a57d812588e9c0 to your computer and use it in GitHub Desktop.
Save sakapon/d0d1f80395740c2488a57d812588e9c0 to your computer and use it in GitHub Desktop.
URL Encoding / HttpClient
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace UnitTest.Client
{
public static class HttpHelper
{
public static string AddQuery(this string uri, IDictionary<string, string> data) =>
$"{uri}?{data.ToFormUrlEncoded()}";
public static string ToFormUrlEncoded(this IDictionary<string, string> data)
{
using (var content = new FormUrlEncodedContent(data))
return content.ReadAsStringAsync().GetAwaiter().GetResult();
}
async public static Task<T> GetAsync<T>(string uri)
{
using (var http = new HttpClient())
{
var response = await http.GetAsync(uri);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<T>();
}
}
async public static Task<T> PostAsFormAsync<T>(string uri, IDictionary<string, string> data)
{
using (var http = new HttpClient())
{
var response = await http.PostAsync(uri, new FormUrlEncodedContent(data));
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<T>();
}
}
}
}
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTest.Client
{
[TestClass]
public class UriQueryTest
{
[TestMethod]
public void Get_Segment()
{
// http://localhost:1961/api/uriquery/Hello~%2C%20World%21
var uri = $"http://localhost:1961/api/uriquery/{Uri.EscapeDataString("Hello~, World!")}";
var result = HttpHelper.GetAsync<string>(uri).GetAwaiter().GetResult();
}
[TestMethod]
public void Get_Query()
{
var data = new Dictionary<string, string>
{
{ "id", "Hello, the \"World+\"." },
};
// http://localhost:1961/api/uriquery?id=Hello%2C+the+%22World%2B%22.
var uri = "http://localhost:1961/api/uriquery".AddQuery(data);
var result = HttpHelper.GetAsync<string>(uri).GetAwaiter().GetResult();
}
[TestMethod]
public void Post_Form()
{
var data = new Dictionary<string, string>
{
{ "name", "Hello, the \"World+\"." },
};
var uri = "http://localhost:1961/api/uriquery";
var result = HttpHelper.PostAsFormAsync<string>(uri, data).GetAwaiter().GetResult();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment