ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

openlayers-WFS跨域请求 使用代理(有可能解决路径问题)

2022-06-15 10:04:32  阅读:174  来源: 互联网

标签:跨域 getHeader request connection openlayers proxy WFS null response


通常web项目于gis服务器不在同一域下,这就涉及到了wfs跨域问题。 1 c#代理
  1. using System;  
  1. using System.Collections.Generic;  
  1. using System.Linq;  
  1. using System.Web;  
  1. using System.Net;  
  1. using System.IO;  
  1.   
  1. namespace WebApplication1  
  1. {  
  1.     ///   
  1.     /// OpenlayerProxy 的摘要说明  
  1.     ///   
  1.     public class OpenlayerProxy : IHttpHandler  
  1.     {  
  1.         public void ProcessRequest(HttpContext context)  
  1.         {  
  1.             if (string.IsNullOrEmpty(context.Request["URL"])) return;  
  1.             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(context.Request["URL"]);  
  1.             request.UserAgent = context.Request.UserAgent;  
  1.             request.ContentType = context.Request.ContentType;  
  1.             request.Method = context.Request.HttpMethod;  
  1.   
  1.             byte[] trans = new byte[1024];  
  1.             int offset = 0;  
  1.             int offcnt = 0;  
  1.   
  1.             if (request.Method.ToUpper() == "POST")  
  1.             {  
  1.                 Stream nstream = request.GetRequestStream();  
  1.                 while (offset < context.Request.ContentLength)  
  1.                 {  
  1.                     offcnt = context.Request.InputStream.Read(trans, offset, 1024);  
  1.                     if (offcnt > 0)  
  1.                     {  
  1.                         nstream.Write(trans, 0, offcnt);  
  1.                         offset += offcnt;  
  1.                     }  
  1.                 }  
  1.                 nstream.Close();  
  1.             }  
  1.             HttpWebResponse response = (HttpWebResponse)request.GetResponse();  
  1.             //Encoding enc = Encoding.GetEncoding(65001);  
  1.             context.Response.ContentType = response.ContentType;  
  1.             StreamReader loResponseStream = new StreamReader(response.GetResponseStream());  
  1.             string lcHtml = loResponseStream.ReadToEnd();  
  1.             context.Response.Write(lcHtml);  
  1.             response.Close();  
  1.             loResponseStream.Close();  
  1.   
  1.         }  
  1.   
  1.         public bool IsReusable  
  1.         {  
  1.             get  
  1.             {  
  1.                 return false;  
  1.             }  
  1.         }  
  1.   
  1.     }  
  1. }  
2 基于java的servlet
  1. package com.nkstar.action;  
  1.   
  1. import javax.servlet.http.HttpServlet;  
  1. import java.io.IOException;  
  1. import java.io.InputStream;  
  1. import java.io.OutputStream;  
  1. import java.net.HttpURLConnection;  
  1. import java.net.URL;  
  1.   
  1. import javax.servlet.ServletException;  
  1. import javax.servlet.http.HttpServlet;  
  1. import javax.servlet.http.HttpServletRequest;  
  1. import javax.servlet.http.HttpServletResponse;  
  1.   
  1. /** 
  1.  * This is a transparent HTTP proxy written in Java that is similar to the proxy 
  1.  * in the OpenLayers examples, which is written in Python. These proxies are 
  1.  * used to circumvent browser restrictions on cross-domain requests with 
  1.  * Javascript. 
  1.  * 

     

     
  1.  * 

     

  1.  * To use the proxy you need to 1) configure the proxy servlet in your web.xml 
  1.  * and 2) use OpenLayers.setProxyHost to set the url-path to the proxy. If the 
  1.  * proxy is configured to listen to the url-pattern '/gwtOpenLayersProxy/*' then 
  1.  * the proxy host should be set to 'gwtOpenLayersProxy?targetURL='. 
  1.  * 

     

     
  1.  * Initial code for this proxy is based upon  
  1.  * "http://trac.openlayers.org/changeset/8099/sandbox?format=diff&new=8099">the 
  1.  * following code
     
  1.  * see also  
  1.  * "http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html" 
  1.  * title="this networking tutorial">this networking tutorial 
  1.  * 

     

  1.  */  
  1. @SuppressWarnings("serial")  
  1. public class OpenLayersProxyServlet extends HttpServlet {  
  1.   
  1.     protected void doGet(HttpServletRequest request,  
  1.             HttpServletResponse response) throws ServletException, IOException {  
  1.         processRequest(request, response);  
  1.     }  
  1.   
  1.     protected void doPost(HttpServletRequest request,  
  1.             HttpServletResponse response) throws ServletException, IOException {  
  1.         processRequest(request, response);  
  1.     }  
  1.   
  1.     private void processRequest(HttpServletRequest request,  
  1.             HttpServletResponse response) throws ServletException, IOException {  
  1.   
  1.         HttpURLConnection connection = null;  
  1.         InputStream istream = null; // input to proxy  
  1.         OutputStream ostream = null; // output from proxy  
  1.         InputStream connectionIstream = null; // output for the target is  
  1.         // input for the connection  
  1.         OutputStream connectionOstream = null; // input for the target is  
  1.         // output for the connection  
  1.   
  1.         String remoteHost = request.getRemoteHost(); // get host address of  
  1.         // client - for checking  
  1.         // allowedHosts  
  1.         boolean allowedHost = isAllowedHost(remoteHost); // The allowedHosts  
  1.         // are the hosts  
  1.         // that are allowed  
  1.         // to use the Open  
  1.         // Proxy.  
  1.         try {  
  1.             // easy way to ignore case of param?  
  1.             if (request.getParameter("targetURL") != null  
  1.                     && request.getParameter("targetURL") != "" && allowedHost) {  
  1.   
  1.                 // HTTPUrlConnection looks at http.proxyHost and http.proxyPort  
  1.                 // system properties.  
  1.                 // Make sure these properties are set these if you are behind a  
  1.                 // proxy.  
  1.   
  1.                 // step 1: initialize  
  1.                 String requestMethod = request.getMethod();  
  1.   
  1.                 URL targetURL = new URL(request.getParameter("targetURL"));  
  1.                 connection = (HttpURLConnection) targetURL.openConnection();  
  1.                 connection.setRequestMethod(requestMethod);  
  1.                 transferHTTPRequestHeaders(connection, request);  
  1.   
  1.                 // step 2: proxy requests  
  1.                 if (requestMethod.equals("GET")) {  
  1.                     // default for setDoInput is true  
  1.                     connectionIstream = connection.getInputStream();  
  1.                 }  
  1.                 ;  
  1.                 if (requestMethod.equals("POST")) {  
  1.                     transferHTTPRequestHeadersForPOST(connection, request);  
  1.                     int clength = request.getContentLength();// clength is  
  1.                     // for checking  
  1.                     // if there is a  
  1.                     // POST body. Is  
  1.                     // that  
  1.                     // sufficient?  
  1.   
  1.                     if (clength > 0) {  
  1.                         istream = request.getInputStream();  
  1.                         connection.setDoOutput(true);// for POST we need to  
  1.                         // write to connection  
  1.                         connection.setRequestProperty("Content-Length", Integer  
  1.                                 .toString(clength)); // only valid for POST  
  1.                         // request  
  1.                         connectionOstream = connection.getOutputStream();  
  1.                         // copy the request body to remote outputStream  
  1.                         copy(istream, connectionOstream);  
  1.                     }  
  1.                     connectionIstream = connection.getInputStream();  
  1.                 }  
  1.   
  1.                 // step 3: return output  
  1.                 // can output be the same for GET/POST? or different return  
  1.                 // headers?  
  1.                 // servlet may return 3 things: status code, response headers,  
  1.                 // response body  
  1.                 // status code and headers have to be set before response body  
  1.                 response.setContentType(connection.getContentType());  
  1.                 ostream = response.getOutputStream();  
  1.                 copy(connectionIstream, ostream);  
  1.             }  
  1.             // if not targetURL send page that targetURL is required param  
  1.         } catch (Exception e) {  
  1.             response.setStatus(500); // what will user get? default page for  
  1.             // response code  
  1.             // WMS/WFS have specific responses to errors  
  1.             // response.getWriter();//will writing custom result help  
  1.             e.printStackTrace();  
  1.         } finally {  
  1.             if (istream != null) {  
  1.                 istream.close();  
  1.             }  
  1.             if (ostream != null) {  
  1.                 ostream.close();  
  1.             }  
  1.             if (connectionIstream != null) {  
  1.                 connectionIstream.close();  
  1.             }  
  1.             if (connectionOstream != null) {  
  1.                 connectionOstream.close();  
  1.             }  
  1.         }  
  1.   
  1.     }  
  1.   
  1.     private void copy(InputStream istream, OutputStream ostream)  
  1.             throws Exception {  
  1.         int bufferSize = 4 * 4 * 1024;// same buffer size as in Jetty utils  
  1.         // (2*8192)  
  1.         byte[] buffer = new byte[bufferSize];  
  1.         int read;  
  1.         while ((read = istream.read(buffer)) != -1) {  
  1.             ostream.write(buffer, 0, read);  
  1.         }  
  1.     }  
  1.   
  1.     private void transferHTTPRequestHeaders(HttpURLConnection connection,  
  1.             HttpServletRequest request) {  
  1.         // TODO make sure all headers are copied to target, see for HTTP headers  
  1.         // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html  
  1.         // Do request.getProperties to get request properties  
  1.         if (request.getHeader("Accept") != null) {  
  1.             connection  
  1.                     .setRequestProperty("Accept", request.getHeader("Accept"));  
  1.         }  
  1.         if (request.getHeader("Accept-Charset") != null) {  
  1.             connection.setRequestProperty("Accept-Charset", request  
  1.                     .getHeader("Accept-Charset"));  
  1.         }  
  1.         if (request.getHeader("Accept-Encoding") != null) {  
  1.             // TODO browsers accept gzipped, should proxy accept gzip and how to  
  1.             // handle it?  
  1.             // connection.setRequestProperty("Accept-Encoding",  
  1.             // request.getHeader("Accept-Encoding"));  
  1.         }  
  1.         if (request.getHeader("Authorization") != null) {  
  1.             connection.setRequestProperty("Authorization", request  
  1.                     .getHeader("Authorization"));  
  1.         }  
  1.         if (request.getHeader("Connection") != null) {  
  1.             // TODO HTTP/1.1 proxies MUST parse the Connection header field  
  1.             // before a message is forwarded and, for each connection-token in  
  1.             // this field, remove any header field(s) from the message with the  
  1.             // same name as the connection-token.  
  1.             // connection.setRequestProperty("Connection",  
  1.             // request.getHeader("Connection"));  
  1.         }  
  1.   
  1.         // set de-facto standard proxy headers (x-forwarded-for, others?s)  
  1.         if (request.getHeader("X-Forwarded-For") != null) {  
  1.             connection.setRequestProperty("X-Forwarded-For", request  
  1.                     .getHeader("X-Forwarded-For"));// TODO append IP proxy  
  1.         } else {  
  1.             connection.setRequestProperty("X-Forwarded-For", request  
  1.                     .getRemoteAddr());// TODO append IP proxy  
  1.         }  
  1.     }  
  1.   
  1.     private void transferHTTPRequestHeadersForPOST(  
  1.             HttpURLConnection connection, HttpServletRequest request) {  
  1.         if (request.getHeader("Content-Type") != null) {  
  1.             connection.setRequestProperty("Content-Type", request  
  1.                     .getContentType());  
  1.         } else {  
  1.             // throw exception?  
  1.         }  
  1.     }  
  1.   
  1.     private boolean isAllowedHost(String remoteHost) {  
  1.         // TODO checking of host  
  1.         return true;  
  1.     }  
  1.   
  1. }  
ashx,servlet这两种直接可以放在web项目当中部署,简单操作。   使用说明 OpenLayer2代理使用,只需在程序开头或init方法第一句写上proxyhost即可。 [javascript]  view plain  copy    
  1. OpenLayers.ProxyHost = '/OpenlayerProxy.ashx?URL=';  
  1.   
  1.   var url = 'http://localhost:8090/geoserver/wfs?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&OUTPUTFORMAT=GML2&TYPENAME=pgrouting:Mypgrouting&viewparams=' + viewparams;  
  1.         var request = OpenLayers.Request.POST({  
  1.             url: url,  
  1.             callback: onComplete  
  1.         });  
  OpenLayer3 代理使用  
  1. queryButton.addEventListener('click', function (event) {  
  1.        var viewparams = "ARRAY[[" + locatearr.join("],[") + "]]";  
  1.        viewparams = stringReg(viewparams);  
  1.        viewparams = "destinationarr:" + viewparams;  
  1.        var url ='http://localhost:8090/geoserver/wfs?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&OUTPUTFORMAT=json&TYPENAME=pgrouting:Mypgrouting&viewparams=' + viewparams;  
  1.        url = '/OpenlayerProxy.ashx?URL=' + encodeURIComponent(url);  
  1.        $.ajax({  
  1.            type: "POST",  
  1.            url: url,  
  1.            dataType:"text",  
  1.            success: onComplete  
  1.        });  
  1.    });  
  需要对url进行编码,否则代理进去丢失参数。   3 使用cros 3.1 下载地址:http://yunpan.cn/cF2sB2L7wuDSS  访问密码 1091   3.2 下载后解压,得到的是org/mortbay/servlets/CrossOriginFilter.class文件,把此文件复制到安装目录下的WEB-INF/classes文件夹中,在我电脑上的路径为:GeoServer 2.7.0\webapps\geoserver\WEB-INF\classes\org\mortbay\servlets\CrossOriginFilter.class. 3.3 打开geoserver安装目录下的web.xml文件,我的电脑上路径为:GeoServer 2.7.0\webapps\geoserver\WEB-INF\web.xml 3.4 在filter集合末尾额外添加一个filter:         cross-origin              org.mortbay.servlets.CrossOriginFilter               allowedOrigins         *                    allowedMethods        GET,POST                    allowedHeaders       X-Requested-With,Content-Type,Accept,Origin             3.5 在filter-mapping末尾额外添加一个filter-mapping           cross-origin         /*     3.6 重启GeoServer服务即可。 优点:post,get跨域请求即可。   4 使用jsonp 4.1  打开geoserver安装目录下的web.xml文件,我的电脑上路径为:GeoServer 2.7.0\webapps\geoserver\WEB-INF\web.xml 4.2 将jsonp注释取消 0   4.3 重启GeoServer。   4.4 使用示例  
  1. function getFeature(options)  
  1. {  
  1.     $.ajax(Global360Val.gisserverhost+'geoserver/wfs',{  
  1.         type: 'GET',  
  1.         data: {  
  1.             service: 'WFS',  
  1.             version: '1.1.0',  
  1.             request: 'GetFeature',  
  1.             typename: options.typename,  
  1.             srsname: options.srid,  
  1.             outputFormat: 'text/javascript',  
  1.             viewparams:options.viewparams,  
  1.             bbox:(options.extent===undefined)?undefined:options.extent.join(',') +  ','+options.srid,//与filter只能用一个  
  1.             filter:options.filter  
  1.         },  
  1.         dataType: 'jsonp',  
  1.         jsonpCallback:'callback:'+options.callback,  
  1.         jsonp:'format_options'  
  1.     });  
  1.   
  1. }  
 
  1.  Source.deviceSource=new ol.source.Vector();  
  1.     getFeature({  
  1.         typename:'tb_place_management',  
  1.         callback:'loadDevice'  
  1.     });  
  1. function loadDevice(res){  
  1.     var features=geojsonFormat.readFeatures(res);  
  1.     Source.deviceSource.addFeatures(features);  
  1. }  
优点:无需安装插件,取消注释即可。 缺点:jsonb只能get,对于参数过长的url的get会失败。不能post,所以提交xml,或者wfs_t都不行。 完毕!      

标签:跨域,getHeader,request,connection,openlayers,proxy,WFS,null,response
来源: https://www.cnblogs.com/devgis/p/16377277.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有