using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using Newtonsoft.Json;
namespace Test.A
{
public static class HttpHelper
{
public static T PostHttps<T>(string url, Dictionary<string, string> parameters, object[] args) where T : new()
{
// 这里设置了协议类型。把SSL验证的设置写到HttpRequect创建之前
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = 30000;
//处理参数列表
var sb = new StringBuilder();
foreach (var item in parameters)
{
//sb.AppendFormat("{0}={1}&", item.Key, item.Value);
sb.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(item.Key), HttpUtility.UrlEncode(item.Value));
}
var paramStr = sb.ToString().TrimEnd('&');
byte[] data = Encoding.UTF8.GetBytes(paramStr);
request.ContentLength = data.Length;
Stream writer = request.GetRequestStream();
writer.Write(data, 0, data.Length);
writer.Close();
StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8);
var resultStr = sr.ReadToEnd();
return JsonConvert.DeserializeObject<T>(resultStr);
}
}
}