{
//类似浏览器确认证书合法方法的绑定
ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
System.Net.WebRequest request = HttpWebRequest.Create(url);
request.Method = "POST";
request.Timeout = 20000;
HttpWebResponse response = null;
try
{
//post提交数据
if (!string.IsNullOrEmpty(postdata))
{
byte[] bytes = Encoding.UTF8.GetBytes(postdata);
request.ContentType = "application/x-www-form-urlencoded";
Stream sendStream = request.GetRequestStream();
sendStream.Write(bytes, 0, bytes.Length);
}
response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(response.StatusDescription);
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
catch (Exception e)
{
return e.Message;
}
}
//该方法用于验证服务器证书是否合法,当然可以直接返回true来表示验证永远通过。服务器证书具体内容在参数certificate中。可根据个人需求验证
//该方法在request.GetResponse()时触发
private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
//为了通过证书验证,总是返回true
return true;
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
private string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt32(ts.TotalSeconds).ToString();
}
/// <summary>
/// 生成随机字符串
/// </summary>
/// <param name="strPwChar">传入生成的随机字符串可以使用哪些字符</param>
/// <param name="intlen">传入生成的随机字符串的长度</param>
private static string MakePassword(string strPwChar, int intlen)
{
string strRe = "";
int iRandNum;
Random rnd = new Random();
for (int i = 0; i < intlen; i++)
{
iRandNum = rnd.Next(strPwChar.Length);
strRe += strPwChar[iRandNum];
}
return strRe;
}
/// <summary>
/// 获取随机字符串
/// </summary>
/// <returns></returns>
private string GetNonce()
{
//设定字符范围为:大小写字母及数字的随机字符串.
string strPwChar = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//截取长度为20
string strNewPW = MakePassword(strPwChar,20);
return strNewPW;
}