C# HttpWebRequest发送post请求调用API
最近有用到C#客户端调用Java开发服务端的需求,将httphelper分享出来给需要的朋友。
public class HttpHelper
{
static QRConfig _Config = new QRConfig();
public static string PostForm(string url, Dictionary<string, string> datas)
{
HttpWebRequest request = null;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
// 这里设置了协议类型。
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;// SecurityProtocolType.Tls1.2;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = 100;
ServicePointManager.Expect100Continue = false;
X509Certificate cerCaiShang = new X509Certificate(_Config.PfxFile, _Config.CER_CODE);
request = WebRequest.Create(url) as HttpWebRequest;
request.ClientCertificates.Add(cerCaiShang);
request.ProtocolVersion = HttpVersion.Version11;
request.KeepAlive = false;
}
else
{
request = (HttpWebRequest)WebRequest.Create(url);
}
request.Method = "POST"; //使用get方式发送数据
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = null;
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.Accept = "*/*";
request.Timeout = 1000 * 5;
byte[] data = Encoding.UTF8.GetBytes(BuildQuery(datas));
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
//获取网页响应结果
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
//client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string result = string.Empty;
using (StreamReader sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
return result;
}
public static string PostUrl(string url, string postData)
{
HttpWebRequest request = null;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
// 这里设置了协议类型。
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;// SecurityProtocolType.Tls1.2;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = 100;
ServicePointManager.Expect100Continue = false;
X509Certificate cerCaiShang = new X509Certificate(_Config.PfxFile, _Config.CER_CODE);
request = WebRequest.Create(url) as HttpWebRequest;
request.ClientCertificates.Add(cerCaiShang);
request.ProtocolVersion = HttpVersion.Version11;
request.Timeout = 1000 * 5;
request.KeepAlive = false;
}
else
{
request = (HttpWebRequest)WebRequest.Create(url);
}
request.Method = "POST"; //使用get方式发送数据
request.ContentType = "application/json";
request.Referer = null;
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.Accept = "*/*";
request.Timeout = 1000 * 10;
byte[] data = Encoding.UTF8.GetBytes(postData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
//获取网页响应结果
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
string result = string.Empty;
using (StreamReader sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
return result;
}
public static string Post(string url, object postData)
{
HttpWebRequest request = null;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
// 这里设置了协议类型。
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;// SecurityProtocolType.Tls1.2;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = 100;
ServicePointManager.Expect100Continue = false;
X509Certificate cerCaiShang = new X509Certificate(_Config.PfxFile, _Config.CER_CODE);
request = WebRequest.Create(url) as HttpWebRequest;
request.ClientCertificates.Add(cerCaiShang);
request.ProtocolVersion = HttpVersion.Version11;
request.Timeout = 1000 * 5;
request.KeepAlive = false;
}
else
{
request = (HttpWebRequest)WebRequest.Create(url);
}
var d1 = JsonConvert.SerializeObject(postData);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(postData.GetType());
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, postData);
byte[] dataBytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(dataBytes, 0, (int)stream.Length);
var bs = dataBytes;
request.Method = "POST"; //使用get方式发送数据
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = null;
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.Accept = "*/*";
request.Timeout = 1000 * 5;
request.ContentLength = bs.Length;
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
//获取网页响应结果
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamres = response.GetResponseStream();
//client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string result = string.Empty;
using (StreamReader sr = new StreamReader(streamres))
{
result = sr.ReadToEnd();
}
return result;
}
//组装请求参数
private static string BuildQuery(IDictionary<string, string> parameters, string encode="utf8")
{
StringBuilder postData = new StringBuilder();
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name))
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
if (encode == "gb2312")
{
postData.Append(Uri.EscapeDataString(value));
}
else if (encode == "utf8")
{
postData.Append(Uri.EscapeDataString(value));
}
else
{
postData.Append(value);
}
hasParam = true;
}
}
return postData.ToString();
}
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
}
调用方法:
urlData += "&sign="+ Uri.EscapeDataString(data.sign);
var res = HttpHelper.PostUrl(Config.SERVER_URL, urlData);