httphelper
public class HttpHelper
{
public static string Post(string url, string paramData)
{
return Post(url, paramData, Encoding.UTF8);
}
public static string Post(string url, string paramData, Encoding encoding)
{
string result;
if (url.ToLower().IndexOf("https", System.StringComparison.Ordinal) > -1)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => { return true; });
}
try
{
var wc = new WebClient();
if (string.IsNullOrEmpty(wc.Headers["Content-Type"]))
{
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
}
wc.Encoding = encoding;
result = wc.UploadString(url, "POST", paramData);
}
catch (Exception e)
{
throw;
}
return result;
}
public static string Get(string url)
{
return Get(url, Encoding.UTF8);
}
public static string Get(string url, Encoding encoding)
{
try
{
var wc = new WebClient { Encoding = encoding };
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
return result;
}
}
catch (Exception e)
{
throw e;
}
}
public static string PostData(string url, NameValueCollection parameters)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
Encoding encoding = Encoding.UTF8;
var parassb = new StringBuilder();
foreach (string key in parameters.Keys)
{
if (parassb.Length > 0)
{
parassb.Append("&");
}
parassb.AppendFormat("{0}={1}", key, HttpUtility.UrlEncode(parameters[key]));
}
byte[] bs = Encoding.UTF8.GetBytes(parassb.ToString());
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}
string result = String.Empty;
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
{
result = reader.ReadToEnd();
}
return result;
}
}
}
使用示例:
var data = "{\"touser\":\"Rich\" },";
data += "{\"msgtype\": \"text\"},";
data += "{\"text\": [{\"content\": \"test\"}]}";
var json = HttpHelper.Post("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken, data);
var parameters = new NameValueCollection { { "Aid", dModel.Aid }, { "Oid", dModel.Oid }, { "Uid", dModel.Uid }, { "Cid", dModel.Coupon }, { "CidD", dModel.Usedt.ToString() }, { "Info", dModel.Info }, { "Return", dModel.ReturnVal } };
HttpHelper.PostData("http://www.baidu.com", parameters);