NetHelp是一个对WebRequest对象的封装,实现了极简的方式对接API的功能。
我们平时在开发过程中难免会遇到需要对接别人提供的API的情况,而对接API主要根据不同的方法类型分为:Get和Post两种。我们在NetHelp里面特地提供了两个静态方法,方便我们可以高效地对接WebAPI。
在对接Http方法为Get的API接口时,我们实现起来是最简单的,只需要一个Url参数即可完成。
Vb.Net |
'定义一个网址 Dim strURL As String="http://pv.sohu.com/cityjson" '直接根据网址返回获取的值 Dim strReturn As String=NetHelp.NetGet(strURL) '我们可以对返回的值进行相应的处理 MessageBox.Show(strReturn) |
C# |
// 定义一个网址 string strURL = "http://pv.sohu.com/cityjson"; // 直接根据网址返回获取的值 string strReturn = NetHelp.NetGet(strURL); // 我们可以对返回的值进行相应的处理 MessageBox.Show(strReturn); |
上面的代码其实最主要的就是中间那一句代码。Get方法的API有一个特点,就是我们可以将URL放到浏览器里面直接显示接口返回的数据。所以对接起来也最简单,只要网址正确,能在浏览器里面正常返回数据,直接替换到上面的代码中即可获得接口的数据。
对接Post方法相对复杂一点,我们也相对地提供了一个NetHelp.NetPost静态方法。
参数说明 | 说明 |
url | 必填项,字符串类型,API接口的网址。不包含参数部分。 |
postData | 必填项,字符串类型,向接口推送的参数组合。例如:index=0&count=1 |
strContentType | 可选项,字符串类型,参数的数据类型,默认值为:application/x-www-form-urlencoded; charset=UTF-8,我们可以通过NetHelp.NetContentType指定不同类型。 |
headersAdd | 可选项,Dictionary<string, string>类型,要添加到Header中的键值字典。 |
beforeGetOrPostDataDelegate | 可选项,NetHelp.BeforeGetOrPostData(WebRequest request)委托类型,我们可以在发送信息之前对WebRequest对象进行一些处理 |
或者使用另外一个重载方法
参数说明 | 说明 |
url | 必填项,字符串类型,API接口的网址。不包含参数部分。 |
postDataDictionary | 必填项,IDictionary<string, string>类型,向接口推送的参数字典对象。方便我们可以不用自己将参数键值对转换成发送数据。 |
strContentType | 可选项,字符串类型,参数的数据类型,默认值为:application/x-www-form-urlencoded; charset=UTF-8,我们可以通过NetHelp.NetContentType指定不同类型。 |
headersAdd | 可选项,Dictionary<string, string>类型,要添加到Header中的键值字典。 |
beforeGetOrPostDataDelegate | 可选项,NetHelp.BeforeGetOrPostData(WebRequest request)委托类型,我们可以在发送信息之前对WebRequest对象进行一些处理 |
Vb.Net |
'定义一个字典,用来保存传递参数键值对 Dim dic As New Dictionary(Of String,String) dic("index")="0" dic("count")="1" '定义一个网址,Post方法网址中不能包含参数 Dim strUrl As String="http://192.168.1.16/person/query/part" '我们可以通过NetHelp的ConvertDictionaryToPostData静态方法,将字典转换成相应的参数 Dim strPostData As String=NetHelp.ConvertDictionaryToPostData(dic) '显示一下转换后的字符串是什么样子的 Proj.MsgDebug.Add(strPostData) '直接根据已有条件获得返回数据 Dim json As String =NetHelp.NetPost(strUrl,strPostData,NetHelp.NetContentType.form) '方法二,我们可以利用第二个重载,直接将字典传递进第二个参数中,而不需要自己去转换 json=NetHelp.NetPost(strUrl,dic,NetHelp.NetContentType.form) '如果返回的数据是一个Json对象,可以转换一下 Dim jo As JObject = JObject.Parse(json) Proj.MsgDebug.Add(jo.ToString()) |
C# |
// 定义一个字典,用来保存传递参数键值对 Dictionary<string, string> dic = new Dictionary<string, string>(); dic["index"] = "0"; dic["count"] = "1"; // 定义一个网址,Post方法网址中不能包含参数 string strUrl = "http://192.168.1.16/person/query/part"; // 我们可以通过NetHelp的ConvertDictionaryToPostData静态方法,将字典转换成相应的参数 string strPostData = NetHelp.ConvertDictionaryToPostData(dic); // 显示一下转换后的字符串是什么样子的 Proj.MsgDebug.Add(strPostData); // 直接根据已有条件获得返回数据 string json = NetHelp.NetPost(strUrl, strPostData, NetHelp.NetContentType.form); // 方法二,我们可以利用第二个重载,直接将字典传递进第二个参数中,而不需要自己去转换 json = NetHelp.NetPost(strUrl, dic, NetHelp.NetContentType.form); // 如果返回的数据是一个Json对象,可以转换一下 JObject jo = JObject.Parse(json); Proj.MsgDebug.Add(jo.ToString()); |
可是很多时候我们对接API时会遇到各种各样的其他需求,比如说接口参数需要根据特定的算法进行加密或者生成验证码。这时候我们可能就需要了解一些其他的知识了。
1、如果需要在Header里面添加一些参数,可以考虑在NetGet和NetPost的headersAdd参数部位传递一个字典进去,这个字典中的值最终会被添加到WebRequest的Header里面。
2、如果需要对传入的参数进行排序的话,可以考虑使用SortedDictionary,这个字典会自动根据Key值进行排序,然后结合NetHelp.ConvertDictionaryToPostData方法来生成相应的参数值。
3、如果需要用到加密相关的功能的话,可以参考Crypt静态类。
4、如果遇到更高级的功能,需要做一些对WebRequest修改属性的事,那么就要用到beforeGetOrPostDataDelegate这个参数了,这是一个委托,有一个WebRequest类型的参数,这个参数就是WebRequest对象的引用,我们就可以直接通过修改此参数对象的属性或者其他功能来实现我们更灵活的自定义。
下面我们就以一个需要证书验证的场景来演示一下如何对接API。
Vb.Net |
Public Sub SmButton1_Click(sender As Object,e As System.EventArgs) '定义一个字典,用来保存传递参数键值对 Dim dic As New Dictionary(Of String,String) dic("index")="0" dic("count")="1" '定义一个网址,Post方法网址中不能包含参数 Dim strUrl As String="http://192.168.1.16/person/query/part" Dim json As String=NetHelp.NetPost(strUrl,dic,NetHelp.NetContentType.form,Nothing,AddressOf ChangeRequestSetting) '如果返回的数据是一个Json对象,可以转换一下 Dim jo As JObject = JObject.Parse(json) MessageBox.Show(jo.ToString()) End Sub Public Sub ChangeRequestSetting(request As System.Net.WebRequest) '指定接口的权限验证等级. request.AuthenticationLevel = Net.Security.AuthenticationLevel.MutualAuthRequired '获取或设置由ServicePointManager对象管理的ServicePoint对象所使用的安全协议. System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 Or System.Net.SecurityProtocolType.Ssl3 Or System.Net.SecurityProtocolType.Tls11 Or System.Net.SecurityProtocolType.Tls13 '获取或设置用于验证服务器证书的回调.用于直接回复服务器验证通过. System.Net.ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf CheckValidationResult) '使用一个证书文件初始化X509Certificate2类 Dim strCertPath As String=Path.Combine(Proj.ProjectPath,"Data\cacert.pem") Dim sa As New System.Security.Cryptography.X509Certificates.X509Certificate2(strCertPath) '在此关联的证书集合中添加一个证书 Dim hp As System.Net.HttpWebRequest = CType(request, System.Net.HttpWebRequest) hp.ClientCertificates.Add(sa) End Sub '用来应对API的服务器,当前有 Public Function CheckValidationResult(ByVal sender As Object, ByVal certificate As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal errors As System.Net.Security.SslPolicyErrors) As Boolean Return True End Function |
C# |
public void SmButton1_Click(object sender, System.EventArgs e) { // 定义一个字典,用来保存传递参数键值对 Dictionary<string, string> dic = new Dictionary<string, string>(); dic["index"] = "0"; dic["count"] = "1"; // 定义一个网址,Post方法网址中不能包含参数 string strUrl = "http://192.168.1.16/person/query/part"; string json = NetHelp.NetPost(strUrl, dic, NetHelp.NetContentType.form, null, ChangeRequestSetting); // 如果返回的数据是一个Json对象,可以转换一下 JObject jo = JObject.Parse(json); MessageBox.Show(jo.ToString()); } public void ChangeRequestSetting(System.Net.WebRequest request) { // 指定接口的权限验证等级. request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequired; // 获取或设置由ServicePointManager对象管理的ServicePoint对象所使用的安全协议. System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls13; // 获取或设置用于验证服务器证书的回调.用于直接回复服务器验证通过. System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); // 使用一个证书文件初始化X509Certificate2类 string strCertPath = Path.Combine(Proj.ProjectPath, @"Data\cacert.pem"); System.Security.Cryptography.X509Certificates.X509Certificate2 sa = new System.Security.Cryptography.X509Certificates.X509Certificate2(strCertPath); // 在此关联的证书集合中添加一个证书 System.Net.HttpWebRequest hp = (System.Net.HttpWebRequest)request; hp.ClientCertificates.Add(sa); } // 用来应对API的服务器,当前有 public bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors) { return true; } |