最近在公司项目中使用了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. pytorch入门之安装和配置

    pytorch是一种python接口的深度学习框架,其他的框架还有caffe,tensorflow等等. 1,pytorch目前支持linux和OSX两种系统.支持的Python版本有2.7,3.5, ...

  2. c++ 面试题(C/C++/STL)

    1,智能指针:auto_ptr(c++11 已经弃用),unique_ptr(用于取代 auto_ptr),  shared_ptr,  weak_ptr http://www.cnblogs.com ...

  3. 视频和swf的相对路径加载,卸载

    package com{ import flash.display.MovieClip; import flash.net.NetConnection; import flash.net.NetStr ...

  4. 从零开始学spring cloud(一) -------- spring cloud 简介

    1.微服务简介 1.1.单体架构 一个归档包(例如war格式)包含了应用所有功能的应用程序,我们通常称之为单体应用.架构单体应用的方法论,我们称之为单体应用架构. 缺点:1. 复杂性高以笔者经手的一个 ...

  5. NET Core小细节杂记

    1.中文编码问题: 01.在net core中,使用中文的编码,要先进行注册: //CodePagesEncodingProvider在包System.Text.Encoding.CodePages中 ...

  6. Django通过字段获取关联模型

    #根据字段获取关联表 filter_field_obj=self.model._meta.get_field(filter_field) print('filter_field_obj:',filte ...

  7. CentOS7 开启网卡,设置开机启用网卡

    默认centos和redhat7都是不启用有线网卡的,要么手动开启,要么安装时直接启用(安装时启用网卡和指定IP最省事)! 一 .临时启用网卡,关机或重启后,网络不会自动开启1.使用命令 ip add ...

  8. sql语句-单表查询

    一:单表查询 CREATE TABLE `Score`( `s_id` ), `c_id` ), `s_score` ), PRIMARY KEY(`s_id`,`c_id`) ); ); ); ); ...

  9. oracle数据库卸数及ddl导出

    一.数据库卸数脚本 还是比较明了的,一看就明白. unloaddevice.sh sqlplus atmpbat/atmpbat@inter @"./unloaddevice.sql&quo ...

  10. AX_Function

    formrun.owner().GetItemId() if (fr.name() == formstr(inventTransEditDimensions) || fr.name() == form ...