C# Post HTTP Request
标签:.com public object for www create dict work service
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Network;
using Newtonsoft.Json;
public static class HttpUtility
{
///
/// 创建POST方式的HTTP请求
///
///
///
///
///
///
///
public static HttpWebRequest CreatePostHttpResponse(string url, IDictionarystring, string> parameters, int timeout, string userAgent, CookieCollection cookies)
{
HttpWebRequest request = null;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
request = WebRequest.Create(url) as HttpWebRequest;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//设置代理UserAgent和超时
//request.UserAgent = userAgent;
request.Timeout = timeout;
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
//发送POST数据
if (!(parameters == null || parameters.Count == 0))
{
StringBuilder buffer = new StringBuilder();
int i = 0;
foreach (string key in parameters.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, parameters[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, parameters[key]);
i++;
}
}
byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
return request;
}
///
/// Post接口
///
///
///
///
///
///
///
public static async Task PostHttpRequest(string url,IDictionarystring, string> parameters, int timeout, string userAgent, CookieCollection cookies)
{
var req = CreatePostHttpResponse(url, parameters, timeout, userAgent, cookies);
var res = await req.GetResponseAsync();
if (null == res)
{
return null;
}
using (Stream s = res.GetResponseStream())
{
StreamReader reader = new StreamReader(s, Encoding.UTF8);
var temp = reader.ReadToEnd();
if (string.IsNullOrEmpty(temp))
{
return null;
}
return JsonConvert.DeserializeObject(temp);
}
}
///
/// MD5计算
///
///
///
public static string Encrypt_MD5_UTF8(string appKey)
{
MD5 MD5 = new MD5CryptoServiceProvider();
var datSource = Encoding.GetEncoding("utf-8").GetBytes(appKey);
var newSource = MD5.ComputeHash(datSource);
var sb = new StringBuilder(32);
for (var i = 0; i )
{
sb.Append(newSource[i].ToString("x").PadLeft(2, ‘0‘));
}
var crypt = sb.ToString();
return crypt;
}
}
C# Post HTTP Request
标签:.com public object for www create dict work service
原文地址:https://www.cnblogs.com/mrblue/p/8510679.html
评论