前段时间研究了C#的代理程序编写方法,用C#请移步这里:http://tedeum.iteye.com/blog/1883837
今天抄两个java的实现备用,第一段代码:
package org.proxy.servlet; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLDecoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ProxyServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 4191419806910781940L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String query = null; response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); query = request.getParameter("url"); System.out.println(query); //query = "http://www.google.cn/search?hl=zh-CN&source=hp&q=proxy&btnG=Google+%E6%90%9C%E7%B4%A2&aq=f&oq="; if (query == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing URL Parameter!"); return; } query = URLDecoder.decode(query); PrintWriter out = response.getWriter(); int length = request.getContentLength(); byte[] bytes = new byte[length]; //System.out.println(length); try{ URL url = new URL(query); BufferedInputStream in = new BufferedInputStream(url.openStream()); System.out.println(in.read(bytes,0,length)); in.close(); out.print(bytes); out.flush(); out.close(); }catch(IOException e){ response.sendError(HttpServletResponse.SC_NOT_FOUND, "Exception:"+e); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String query = null; response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); query = request.getParameter("url"); System.out.println(query); //query = "http://www.google.cn/search?hl=zh-CN&source=hp&q=proxy&btnG=Google+%E6%90%9C%E7%B4%A2&aq=f&oq="; if (query == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing URL Parameter!"); return; } query = URLDecoder.decode(query); PrintWriter out = response.getWriter(); int length = request.getContentLength(); byte[] bytes = new byte[length]; //System.out.println(length); try{ URL url = new URL(query); BufferedInputStream in = new BufferedInputStream(url.openStream()); System.out.println(in.read(bytes,0,length)); in.close(); out.print(bytes); out.flush(); out.close(); }catch(IOException e){ response.sendError(HttpServletResponse.SC_NOT_FOUND, "Exception:"+e); } } }
下面是第二段代码:
package org.gwtopenmaps.openlayers.server; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This is a transparent HTTP proxy written in Java that is similar to the proxy in * the OpenLayers examples, which is written in Python. These proxies are used * to circumvent browser restrictions on cross-domain requests with Javascript. * </p> * <p> * To use the proxy you need to 1) configure the proxy servlet in your web.xml * and 2) use OpenLayers.setProxyHost to set the url-path to the proxy. If the * proxy is configured to listen to the url-pattern '/gwtOpenLayersProxy/*' then * the proxy host should be set to 'gwtOpenLayersProxy?targetURL='. * </p> * Initial code for this proxy is based upon <a href= * "http://trac.openlayers.org/changeset/8099/sandbox?format=diff&new=8099">the * following code</a><br /> * see also <a href= * "http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html" * title="this networking tutorial">this networking tutorial</a> * <p> */ @SuppressWarnings("serial") public class GwtOpenLayersProxyServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpURLConnection connection = null; InputStream istream = null; //input to proxy OutputStream ostream = null; //output from proxy InputStream connectionIstream = null; //output for the target is input for the connection OutputStream connectionOstream = null; //input for the target is output for the connection String remoteHost = request.getRemoteHost(); // get host address of client - for checking allowedHosts boolean allowedHost = isAllowedHost(remoteHost); //The allowedHosts are the hosts that are allowed to use the Open Proxy. try { // easy way to ignore case of param? if(request.getParameter("targetURL") != null && request.getParameter("targetURL") != "" && allowedHost) { // HTTPUrlConnection looks at http.proxyHost and http.proxyPort system properties. // Make sure these properties are set these if you are behind a proxy. //step 1: initialize String requestMethod = request.getMethod(); URL targetURL = new URL(request.getParameter("targetURL")); connection = (HttpURLConnection) targetURL.openConnection(); connection.setRequestMethod(requestMethod); transferHTTPRequestHeaders(connection, request); //step 2: proxy requests if (requestMethod.equals("GET")){ //default for setDoInput is true connectionIstream = connection.getInputStream(); }; if (requestMethod.equals("POST")){ transferHTTPRequestHeadersForPOST(connection, request); int clength = request.getContentLength();//clength is for checking if there is a POST body. Is that sufficient? if(clength > 0) { istream = request.getInputStream(); connection.setDoOutput(true);//for POST we need to write to connection connection.setRequestProperty( "Content-Length",Integer.toString(clength)); //only valid for POST request connectionOstream = connection.getOutputStream(); //copy the request body to remote outputStream copy(istream, connectionOstream); } connectionIstream = connection.getInputStream(); } //step 3: return output //can output be the same for GET/POST? or different return headers? //servlet may return 3 things: status code, response headers, response body // status code and headers have to be set before response body response.setContentType(connection.getContentType()); ostream = response.getOutputStream(); copy(connectionIstream, ostream); } // if not targetURL send page that targetURL is required param } catch (Exception e){ response.setStatus(500); //what will user get? default page for response code //WMS/WFS have specific responses to errors //response.getWriter();//will writing custom result help e.printStackTrace(); } finally { if(istream != null) { istream.close(); } if(ostream != null) { ostream.close(); } if(connectionIstream != null) { connectionIstream.close(); } if(connectionOstream != null) { connectionOstream.close(); } } } private void copy(InputStream istream, OutputStream ostream) throws Exception { int bufferSize = 4*4*1024;//same buffer size as in Jetty utils (2*8192) byte[] buffer = new byte[bufferSize]; int read; while ((read = istream.read(buffer)) != -1) { ostream.write(buffer, 0, read); } } private void transferHTTPRequestHeaders(HttpURLConnection connection, HttpServletRequest request){ //TODO make sure all headers are copied to target, see for HTTP headers http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html //Do request.getProperties to get request properties if(request.getHeader("Accept") != null){ connection.setRequestProperty("Accept", request.getHeader("Accept")); } if(request.getHeader("Accept-Charset") != null){ connection.setRequestProperty("Accept-Charset", request.getHeader("Accept-Charset")); } if(request.getHeader("Accept-Encoding") != null){ //TODO browsers accept gzipped, should proxy accept gzip and how to handle it? //connection.setRequestProperty("Accept-Encoding", request.getHeader("Accept-Encoding")); } if(request.getHeader("Authorization") != null){ connection.setRequestProperty("Authorization", request.getHeader("Authorization")); } if(request.getHeader("Connection") != null){ //TODO HTTP/1.1 proxies MUST parse the Connection header field before a message is forwarded and, for each connection-token in this field, remove any header field(s) from the message with the same name as the connection-token. //connection.setRequestProperty("Connection", request.getHeader("Connection")); } //set de-facto standard proxy headers (x-forwarded-for, others?s) if(request.getHeader("X-Forwarded-For") != null){ connection.setRequestProperty("X-Forwarded-For", request.getHeader("X-Forwarded-For"));//TODO append IP proxy } else{ connection.setRequestProperty("X-Forwarded-For", request.getRemoteAddr());//TODO append IP proxy } } private void transferHTTPRequestHeadersForPOST(HttpURLConnection connection, HttpServletRequest request){ if(request.getHeader("Content-Type") != null){ connection.setRequestProperty( "Content-Type",request.getContentType()); } else { //throw exception? } } private boolean isAllowedHost(String remoteHost){ //TODO checking of host return true; } }
没有细看,仅供参考,貌似网上第二段用得多些。
相关推荐
下面将详细介绍如何解决OpenLayers中的跨域问题。 ### 一、理解同源策略 同源策略是Web浏览器的一项安全措施,它限制了来自不同源(协议、域名、端口)的脚本之间共享资源。例如,一个运行在http://example.com上...
找了很久的下载地址都没有找到,最后终于在一个网页链接中点击直接下载到了,在这里提供资源,有需要的可以下载。
1) 部署到tomcat6的webapps下面。 2) 将world.mbtiles放到D:/gisdata/mbtiles/目录下。 3) 在浏览器输入:(世界地图,图层0-7) http://localhost:8080/MbTileService/local_tiles.html
在某些情况下,由于跨域限制或者安全策略,OpenLayers可能无法直接与GeoServer通信,这时就需要设置代理来实现数据请求。 标题"openlayers geoserver代理的配置文件"涉及到的知识点主要是如何配置OpenLayers和...
本项目实现了基于Java、Geotools、WContour和OpenLayers的等值线等值面功能,下面将详细阐述这些技术及其在实现过程中的作用。 首先,Java是一种广泛使用的编程语言,它提供了丰富的库和框架,适用于开发跨平台的...
总的来说,这个"asp.net mvc openlayers入门小程序"是学习如何在ASP.NET MVC应用中集成地图功能的一个良好起点。开发者不仅可以掌握ASP.NET MVC的基本架构,还能深入理解OpenLayers的使用,以及如何有效地处理和传递...
综上所述,实现OpenLayers3版本的动态标绘API需要理解OpenLayers3的基本架构,掌握图层、控制、几何对象、事件处理、样式以及交互等关键概念。结合提供的Gitee仓库资源,开发者可以快速上手并根据需求定制自己的地图...
该脚本能够实现openlayers-Cesium二三维联动效果的功能
本篇文章将详细讲解如何利用Java、Geotools、WContour以及OpenLayers这四个关键组件,实现等值线和等值面的功能。 首先,Java作为一门广泛使用的编程语言,以其强大的类库和跨平台特性,为开发GIS应用提供了坚实的...
Java+OpenLayers3+GeoServer 二次开发应用
Geoserver是一个基于Java的Web服务,用于发布地图数据,而OpenLayers是一个JavaScript库,用于在Web浏览器中展示这些地图。本篇文章将深入探讨如何配置Geoserver与OpenLayers,以便在Web应用程序中创建交互式的地理...
在微信小程序中,你可以实现类似原生应用的各种功能,包括但不限于页面展示、用户交互、网络通信等。这个"微信小程序常用功能学习示例"是一个很好的学习资源,帮助开发者掌握微信小程序的基础开发技巧。 首先,我们...
例如,使用Java的Servlet或Spring MVC框架提供地图服务,OpenLayers则负责前端展示和用户交互。这需要开发者对HTTP协议、JSON格式以及GeoJSON有一定的理解。 学习OpenLayers时,除了阅读官方文档外,还可以参考示例...
OpenLayers3 Toolkit 针对Openlayers3写的一套工具包,基于v3.15.1版本。 开发计划 目前主要计划完成的功能模块: 快速构建地图 地图大小自适应 常用功能集成 简便画点线面 使用说明 在加载ol3toolkit.js前先加载...
Java作为一种广泛使用的编程语言,也提供了多种方式来实现等值线的绘制。以下是对"java实现的等值线画法"的详细解释: 1. **基本概念**: - **等值线**:等值线是连接数值相等的点的曲线,它将具有相同数值的区域...
ngeo是一个专门针对AngularJS和OpenLayers框架设计的JavaScript库,它的主要目标是简化地理信息系统(GIS)应用的开发过程。在Web GIS领域,AngularJS提供了强大的MVC(Model-View-Controller)框架,而OpenLayers则...
本教程将详细介绍如何使用OpenLayers实现实时定位功能。 实时定位通常涉及到获取用户设备的位置信息,这在现代浏览器中可以通过GPS、Wi-Fi信号或移动网络基站进行。OpenLayers 提供了内置的定位API来处理这些任务。...