[通过HttpWebRequest请求https接口]

£神魔★判官ぃ 2022-09-24 06:24 275阅读 0赞

一.为什么进行代理接口的开发:

有些项目需要访问被墙了哒网站,比如前不久公司开发项目需要使用google地图的接口,而google在中国被墙了,所有打算做一个代理接口服务,将代理放到国外服务器上,通过访问该代理,在代理上请求google地图的接口,实现访问。然而访问的接口通信是采用的https通信,存在证书验证,使用httprequest请求时候需要带上证书进行验证,才能建立正确的链接。(在前一面一篇博客中已经写了如和下载https通信需要的证书)

二.使用HttpWebRequest请求https接口:

新建立mvc项目,添加ProxyApi控制器,在构造函数处验证证书.

  1. public ProxyApiController()
  2. {
  3. ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(VerifyServerCertificate);
  4. }
  5. private bool VerifyServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  6. {
  7. return true;
  8. }

添加Test 的Action,这里需要将被墙的域名添加到配置中,避免被运营商截取到,检查出是访问被墙域名,避免被截掉。后面的parm是请求参数

  1. public ActionResult Test()
  2. {
  3. try
  4. {
  5. string url = ConfigurationManager.AppSettings["domain"] + Request["parm"];
  6. string result = Get(url);
  7. return Content(result);
  8. }
  9. catch (Exception ex)
  10. {
  11. return Content("ERROR:MapAgent>>"+ex.Message);
  12. }
  13. }

进行HttpWebRequest :Get请求,此处的证书是之前翻墙查看到的证书,使用ie浏览器下载的证书,此处的certificate是证书所在绝对路径。

  1. private string Get(string url)
  2. {
  3. try
  4. {
  5. X509Certificate Cert = X509Certificate.CreateFromCertFile(ConfigurationManager.AppSettings["certificate"]); //证书存放的绝对路径
  6. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  7. request.ClientCertificates.Add(Cert);
  8. request.KeepAlive = true;
  9. request.Method = "get";
  10. request.ContentType = "application/x-www-form-urlencoded";
  11. request.ContentLength = 0;
  12. request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36";
  13. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  14. Stream stream = response.GetResponseStream();
  15. StreamReader reader = new StreamReader(stream, Encoding.UTF8);
  16. string result = reader.ReadToEnd();
  17. return result;
  18. }
  19. catch (Exception ex)
  20. {
  21. return "ERROR>>" + ex.Message + " URL:" + url;
  22. }
  23. }

将web发布后布置到国外的服务器,配置好证书地址和需要访问的被墙的谷歌地图域名https://maps.googleapis.com/,将可变的参数进行传递拼接,使用HttpWebRequest进行请求访问,就完成了简单的代理web服务开发。

20160727150626442

发表评论

表情:
评论列表 (有 0 条评论,275人围观)

还没有评论,来说两句吧...

相关阅读