解决https 请求过程中SSL问题
最近一个项目中用到了https的请求,在实际调用过程中发现之前的http方法不支持https,调用一直报错。
查询了一下,添加几行代码解决问题。
public string httppost(string url, string postdatastr, string useragent = null)
{
servicepointmanager.servercertificatevalidationcallback += (s, cert, chain, sslpolicyerrors) => true;//新增一行
system.net.servicepointmanager.securityprotocol = (securityprotocoltype)192 | (securityprotocoltype)768 | (securityprotocoltype)3072;//新增第二行,很重要
servicepointmanager.servercertificatevalidationcallback = new system.net.security.remotecertificatevalidationcallback(checkvalidationresult);//新增第三行
httpwebrequest request = (httpwebrequest)webrequest.create(url);
request.method = "post";
request.contenttype = "application/x-www-form-urlencoded";
request.contentlength = encoding.utf8.getbytecount(postdatastr);
if (!string.isnullorempty(useragent))
{
request.useragent = useragent;
}
stream myrequeststream = request.getrequeststream();
streamwriter mystreamwriter = new streamwriter(myrequeststream, encoding.getencoding("gb2312"));
mystreamwriter.write(postdatastr);
mystreamwriter.close();
httpwebresponse response = (httpwebresponse)request.getresponse();
stream myresponsestream = response.getresponsestream();
streamreader mystreamreader = new streamreader(myresponsestream, encoding.getencoding("utf-8"));
string retstring = mystreamreader.readtoend();
mystreamreader.close();
myresponsestream.close();
return retstring;
}
下一篇: 鸡肉和什么菜炖最好吃,做法详解