欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

解决https 请求过程中SSL问题

程序员文章站 2022-05-18 16:17:08
最近一个项目中用到了https的请求,在实际调用过程中发现之前的http方法不支持https,调用一直报错。 查询了一下,添加几行代码解决问题。 public string HttpPost(string Url, string postDataStr, string useragent = nul ......

最近一个项目中用到了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;
        }