最近在公司项目中使用了HttpWebRequst相关API,运行环境为.Net/Mono 2.0,是一款针对Unity平台的工具。开发过程中碰到了大家可能都碰到过的问题,Http还是Https? 为什么Http可以正常响应,Https就会失败,返回结果为authorize or decrypt failed.

by th way, .Net 4.0及以上版本好像已经没有这个问题了,巨硬默默把坑填了。

使用Http的写法:

public void Get(string Url)
{ HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (Url);
webRequest.Method="GET";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36";
webRequest.BeginGetResponse(GetResponseCallback,webRequest);
} private void GetResponseCallback(IAsyncResult ar)
{
//RequestState myRequestState = (RequestState)ar.AsyncState;
HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;
try{
WebResponse response = webRequest.EndGetResponse(ar);
streamReader = new StreamReader(response.GetResponseStream ());
}
catch(Exception es)
{
Debug.Log (es.Message);
}
if (GetDataCompleted != null) {
GetDataCompleted(this,new GetDataCompletedArgs(streamReader.ReadToEnd ()));
}
}

这里使用了异步,同步的写法效果相同。

但是如果此时使用了Https的Url,结果会一直返回失败。这是为什么呢?原因是Https基于SSL/TLS协议,需要在请求之前进行证书验证,而我们上面的写法并没有进行相关的验证,所以导致通信失败。怎么解决此问题呢?很简单,我们在请求发出前进行验证,在.Net 2.0或更高版本,我们加入回调函数即可。

解决办法:

public void Get(string Url)
{
//SSL/TLS certificate method
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (Url);
webRequest.Method="GET";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36";
webRequest.BeginGetResponse(GetResponseCallback,webRequest);
} /// <summary>
/// SSL/TLS certificate callback method
/// Must return true
/// </summary>
/// <returns><c>true</c>, if validation result was checked, <c>false</c> otherwise.</returns>
/// <param name="sender">Sender.</param>
/// <param name="certificate">Certificate.</param>
/// <param name="chain">Chain.</param>
/// <param name="sslPolicyErrors">Ssl policy errors.</param>
public bool CheckValidationResult (object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
//Debug.LogWarning (certificate.GetSerialNumberString ());
return true;
} /// <summary>
/// Gets the response callback.
/// </summary>
/// <param name="ar">Ar.</param>
private void GetResponseCallback(IAsyncResult ar)
{
//RequestState myRequestState = (RequestState)ar.AsyncState;
HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;
try{
WebResponse response = webRequest.EndGetResponse(ar);
streamReader = new StreamReader(response.GetResponseStream ());
}
catch(Exception es)
{
Debug.Log (es.Message);
}
if (GetDataCompleted != null) {
GetDataCompleted(this,new GetDataCompletedArgs(streamReader.ReadToEnd ()));
}
}

至此就可以,解决此问题,这类问题说大不大,说小不小,属于我们开发中遇到的小坑之一,.Net4.0以上版本不需注意此问题。

关于更低的.Net 1.1的写法,大家可以去看一下博客,本篇博文也是参照他的解决方案:

http://blog.sina.com.cn/s/blog_4ae95c270101qnn1.html

  

HttpWebRequst中https的验证处理问题的更多相关文章

  1. 【腾讯Bugly干货分享】iOS 中 HTTPS 证书验证浅析

    本文来自于腾讯Bugly公众号(weixinBugly),未经作者同意,请勿转载,原文地址:https://mp.weixin.qq.com/s/-fLLTtip509K6pNOTkflPQ 导语 本 ...

  2. https 安全验证问题

    最近为了满足苹果的 https 要求, 经过努力终于写出了方法 验证 SSL 证书是否满足 ATS 要求 nscurl --ats-diagnostics --verbose https://你的域名 ...

  3. Azure Service Bus 中的身份验证方式 Shared Access Signature

    var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...

  4. linux:Nginx+https双向验证(数字安全证书)

    本文由邓亚运提供 Nginx+https双向验证 说明: 要想实现nginx的https,nginx必须启用http_ssl模块:在编译时加上--with-http_ssl_module参数就ok.另 ...

  5. ASP.NET Core WebApi中使用FluentValidation验证数据模型

    原文链接:Common features in ASP.NET Core 2.1 WebApi: Validation 作者:Anthony Giretti 译者:Lamond Lu 介绍 验证用户输 ...

  6. nginx配置https双向验证(ca机构证书+自签证书)

    nginx配置https双向验证 服务端验证(ca机构证书) 客户端验证(服务器自签证书) 本文用的阿里云签发的免费证书实验,下载nginx安装ssl,文件夹有两个文件 这两个文件用于做服务器http ...

  7. 网络基础 记一次HTTPS证书验证测试过程

    记一次HTTPS证书验证测试过程 by:授客 QQ:1033553122 实践 1) 安装证书 选择主机A(假设10.202.95.88)上安装https证书 说明:采用https的服务器,必须安装数 ...

  8. Requests对HTTPS请求验证SSL证书

    SSL证书通过在客户端浏览器和Web服务器之间建立一条SSL安全通道(Secure socket layer(SSL)安全协议是由Netscape Communication公司设计开发.该安全协议主 ...

  9. [转]Reporting Services 中的身份验证类型

    本文转自:https://docs.microsoft.com/zh-cn/previous-versions/sql/sql-server-2008/cc281310%28v%3dsql.100%2 ...

随机推荐

  1. R语言-散点图阵

    1.pairs()函数 > pairs(iris[,1:4]) #取iris数据集的第一列到第四列两两作图 2.plot()函数 > plot(iris[,1:4], + main=&qu ...

  2. 微擎系统jssdk系统快速签名变量

    jssdkconfig = {php echo json_encode($_W['account']['jssdkconfig']);} || { jsApiList:[] };    jssdkco ...

  3. 使用JavaMail发送邮件-从FTP读取图片并添加到邮件正文发送

    业务分析: 最近工作需要,需要从FTP读取图片内容,添加到邮件正文发送.发送邮件正文,添加附件采用Spring的MimeMessageHelper对象来完成,添加图片也将采用MimeMessageHe ...

  4. Linux yum源配置

    Linux yum源配置 本文介绍Red Hat下yum源配置方法,Redhat使用yum网络源需要购买服务,但是本地yum源不会收费. CentOS用户自带yum源,并且yum不收费. 准备工具: ...

  5. node.js中 express + multer 处理文件上传

    multer中间件,可以很方便的结合express处理用户表单上传的文件. 一.安装multer npm install multer 二.处理单个文件上传 const express = requi ...

  6. [字符串]TrBBnsformBBtion

    TrBBnsformBBtion Let us consider the following operations on a string consisting of A and B: Select ...

  7. HDU 5521.Meeting 最短路模板题

    Meeting Time Limit: 12000/6000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)Total ...

  8. Java多线程系列3 synchronized 关键词

    先来看一个线程安全的例子 ,两个线程对count进行累加,共累加10万次. public class AddTest { public static void main(String[] args) ...

  9. qsort例子

    #include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> typ ...

  10. python基本数据类型之字符串(五)

    python基本数据类型之字符串(五) 遍历与查找 python中的字符串属于可迭代对象,通过一些方法可以遍历字符串中的每一个字符.而查找的方法主要有两个:find与index. 1.字符串的遍历 字 ...