Skip to content

Instantly share code, notes, and snippets.

@sakapon
Last active June 22, 2017 06:48
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/d07be0cbf35ddd90eaeffa2b989e2b02 to your computer and use it in GitHub Desktop.
Save sakapon/d07be0cbf35ddd90eaeffa2b989e2b02 to your computer and use it in GitHub Desktop.
ProxySample/DynamicHttpConsole/HttpHelper.cs
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text;
namespace DynamicHttpConsole
{
public static class HttpHelper
{
public static string Get(string uri, object query) =>
query == null ? Get(uri) :
IsPropertiesObject(query) ? Get(uri, ToDictionary(query)) :
Get(uri, new { query });
static bool IsPropertiesObject(object o)
{
if (o == null) return false;
var oType = o.GetType();
return oType.IsClass && oType != typeof(string);
}
static IDictionary<string, object> ToDictionary(object obj) =>
TypeDescriptor.GetProperties(obj)
.Cast<PropertyDescriptor>()
.ToDictionary(p => p.Name, p => p.GetValue(obj));
public static string Get(string uri, IDictionary<string, object> query = null)
{
using (var web = new WebClient { Encoding = Encoding.UTF8 })
{
if (query != null)
web.QueryString = query.ToNameValueCollection();
return web.DownloadString(uri);
}
}
public static NameValueCollection ToNameValueCollection(this IDictionary<string, object> dictionary)
{
var collection = new NameValueCollection();
foreach (var item in dictionary)
collection[item.Key] = item.Value?.ToString();
return collection;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
namespace DynamicHttpConsole
{
class Program
{
// http://zip.cgis.biz/
const string Uri_Cgis_Xml = "http://zip.cgis.biz/xml/zip.php";
static void Main(string[] args)
{
// No query
Console.WriteLine(HttpHelper.Get(Uri_Cgis_Xml));
// Dictionary
Console.WriteLine(HttpHelper.Get(Uri_Cgis_Xml, new Dictionary<string, object> { { "zn", "6048301" } }));
Console.WriteLine(HttpHelper.Get(Uri_Cgis_Xml, new Dictionary<string, object> { { "zn", "501" }, { "ver", 1 } }));
// Anonymous type
Console.WriteLine(HttpHelper.Get(Uri_Cgis_Xml, new { zn = "6050073" }));
Console.WriteLine(HttpHelper.Get(Uri_Cgis_Xml, new { zn = "502", ver = 1 }));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment