一、servlet对象进行转发比较
1、HttpServletRequest对象
request.getRequestDispatcher("/webgame/tencent.do?amt=300&appid=1101819552").include(request,response),方法实现转发,但是只能将请求转发给同一个WEB应用中的组件;
request.getRequestDispatcher("/hanlder/webgame/tencent.do?amt=300&appid=1101819552l").forward(request,response),方法实现请求转发,但是只能将请求转发给同一个WEB应用中的组件,方法的请求转发过程结束后,浏览器地址栏保持初始的URL地址不变。
2、HttpServletResponse对象
response.sendRedirect("http://127.0.0.1:8080/order/hanlder/webgame/tencent.do?amt=300&appid=1101819552l"),方法实现资源重定向,URL以“/”开头,它是相对于整个WEB站点的根目录,方法还可以重定向到同一个站点上的其他应用程序中的资源,甚至是使用绝对URL重定向到其他站点的资源。
二、转发且获取转发地址的返回结果的方法
1、调用转发的类
package com.client.webgames.order; import java.net.URLEncoder; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.support.util.HttpClientUtil; @Controller public class OrderCallbackForTencentWeb { Log log = LogFactory.getLog(this.getClass()); @SuppressWarnings("rawtypes") @RequestMapping("/order/notify/webgame/tencent") @ResponseBody public String handler(HttpServletRequest request, HttpServletResponse response) { int i = 0; //请求参数字符串 StringBuffer urlParams = new StringBuffer(); //拿到页面传过来的键值对,并迭代出所有的键 Iterator itr = request.getParameterMap().keySet().iterator(); while (itr.hasNext()){ String key = itr.next().toString(); //key String value = request.getParameter(key); //value if("sig".equals(key)){ try { value = URLEncoder.encode(value,"UTF-8").replace("+", "%20").replace("*", "%2A"); } catch (Exception e) { e.printStackTrace(); } } if(i == 0){ urlParams.append(key + "=" + value); }else{ urlParams.append("&" + key + "=" + value); } i++; } String url = "http://127.0.0.1:80/order/hanlder/webgame/tencent.do?" + urlParams.toString(); log.info("=-=-=-url=" + url); try { String result = HttpClientUtil.get(url); return result; } catch (Exception e) { e.printStackTrace(); } return "{\"ret\":1,\"msg\":\"FAIL\"}"; } }
2、实现类
package com.support.util; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.HttpURLConnection; import java.net.URL; import java.nio.ByteBuffer; import java.security.Principal; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Iterator; import java.util.Map; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.params.HttpMethodParams; /** * HttpClientUtil */ public class HttpClientUtil { //获得ConnectionManager,设置相关参数 private static MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager(); private static int connectionTimeOut = 60000; private static int socketTimeOut = 50000; private static int maxConnectionPerHost = 10; private static int maxTotalConnections = 50; // 初始化ConnectionManger的方法 static { manager.getParams().setConnectionTimeout(connectionTimeOut); manager.getParams().setSoTimeout(socketTimeOut); manager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost); manager.getParams().setMaxTotalConnections(maxTotalConnections); } public static String get(String urlstr) throws Exception { return get(urlstr, "UTF-8"); } // 通过get方法获取网页内容 public static String get(String url, String responseCharSet) throws HttpException, IOException { // 构造HttpClient的实例 HttpClient client = new HttpClient(manager); // 创建GET方法的实例 GetMethod get = new GetMethod(url); get.setFollowRedirects(true); String result = null; StringBuffer resultBuffer = new StringBuffer(); try { client.executeMethod(get); // 在目标页面情况未知的条件下,不推荐使用getResponseBodyAsString()方法 BufferedReader in = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), get.getResponseCharSet())); String inputLine = null; boolean first = true; while ((inputLine = in.readLine()) != null) { if (first) { first = false; } else { resultBuffer.append("\n"); } resultBuffer.append(inputLine); } in.close(); result = resultBuffer.toString(); // iso-8859-1 is the default reading encode result = HttpClientUtil.ConverterStringCode(resultBuffer.toString(), get.getResponseCharSet(), responseCharSet); } finally { get.releaseConnection(); } return result; } /** * 通过post方法获取网页内容,带参数 */ public static String post(String url, String requestCharSet, String responseCharSet, NameValuePair[] nameValuePair) throws IOException { HttpClient client = new HttpClient(manager); PostMethod post = new CharSetPostMethod(url, requestCharSet); if (nameValuePair != null) { post.setRequestBody(nameValuePair); } post.setFollowRedirects(false); String result = null; StringBuffer resultBuffer = new StringBuffer(); try { client.executeMethod(post); BufferedReader in = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet())); String inputLine = null; while ((inputLine = in.readLine()) != null) { resultBuffer.append(inputLine); resultBuffer.append("\n"); } in.close(); // iso-8859-1 is the default reading encode result = HttpClientUtil.ConverterStringCode(resultBuffer.toString(), post.getResponseCharSet(), responseCharSet); } finally { post.releaseConnection(); } return result; } /** * 通过post方法获取网页内容,带参数 */ public static String post(String url, String requestCharSet, String responseCharSet,String headerValue) throws IOException { HttpClient client = new HttpClient(manager); PostMethod post = new CharSetPostMethod(url, requestCharSet); post.setFollowRedirects(false); String result = null; StringBuffer resultBuffer = new StringBuffer(); try { Header header=new Header("Authorization", headerValue); post.addRequestHeader(header); client.executeMethod(post); BufferedReader in = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet())); String inputLine = null; while ((inputLine = in.readLine()) != null) { resultBuffer.append(inputLine); resultBuffer.append("\n"); } in.close(); // iso-8859-1 is the default reading encode result = HttpClientUtil.ConverterStringCode(resultBuffer.toString(), post.getResponseCharSet(), responseCharSet); } finally { post.releaseConnection(); } return result; } /** * * @param url * @param requestCharSet * @param responseCharSet * @param json 传入json格式参数 * @return * @throws IOException */ public static String postJSON(String url, String requestCharSet, String responseCharSet, String json) throws IOException { HttpClient client = new HttpClient(manager); PostMethod post = new CharSetPostMethod(url, requestCharSet); RequestEntity requestEntity = new StringRequestEntity(json); post.setRequestEntity(requestEntity); post.setFollowRedirects(false); String result = null; StringBuffer resultBuffer = new StringBuffer(); try { client.executeMethod(post); BufferedReader in = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet())); String inputLine = null; while ((inputLine = in.readLine()) != null) { resultBuffer.append(inputLine); resultBuffer.append("\n"); } in.close(); // iso-8859-1 is the default reading encode result = HttpClientUtil.ConverterStringCode(resultBuffer.toString(), post.getResponseCharSet(), responseCharSet); } finally { post.releaseConnection(); } return result; } /** * 通过post方法获取网页内容,不带参数 * * @param url * @param requestCharSet * @param responseCharSet * @return * @throws IOException */ public static String post(String url, String requestCharSet, String responseCharSet) throws IOException { return post(url, requestCharSet, responseCharSet); } /** * 通过post方式提交请求获得文本结果 * * @param urlstr * @param contentCharset * @return * @throws Exception */ public static String post(String url, Map<String, String> paramMap, String contentCharset) throws Exception { NameValuePair[] nameValuePair = null; if (paramMap != null) { nameValuePair = new NameValuePair[paramMap.size()]; int i = 0; Iterator<Map.Entry<String, String>> iter = paramMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); nameValuePair[i++] = (new NameValuePair(entry.getKey(), entry.getValue())); } } return post(url, contentCharset, contentCharset, nameValuePair); } public static String postJSON(String urlstr, String json) throws Exception { return postJSON(urlstr,"UTF-8","UTF-8",json); } public static String post(String urlstr, Map<String, String> paramMap) throws Exception { return post(urlstr, paramMap, "UTF-8"); } public static int getHttpStatusCode(String url) throws HttpException, IOException { HttpClient client = new HttpClient(manager); GetMethod method = new GetMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); int statusCode = 0; try { statusCode = client.executeMethod(method); } finally { method.releaseConnection(); } return statusCode; } private static String ConverterStringCode(String source, String srcEncode, String destEncode) throws UnsupportedEncodingException { if (source != null) { return new String(source.getBytes(srcEncode), destEncode); } else { return ""; } } public static String verifyToken(String url,String body,String mode) { try { //http://192.168.3.251:8080/login/check/lenovo.do URL u = new URL(url); StringBuffer bufer = new StringBuffer(); // bufer.append("token=").append(token).append("&appId=").append(appId); HttpURLConnection urlConnection = (HttpURLConnection) u.openConnection(); // int mTimeOut = back.timeOut(mWhat, mToken); final int timeOut = 10*1000; urlConnection.setConnectTimeout(timeOut); urlConnection.setReadTimeout(timeOut); // HashMap<String, String> mProperty = back.param(mWhat, mToken); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setRequestMethod(mode); byte[] message = body.getBytes(); int length = message.length; urlConnection.setRequestProperty("Content-Length",length+""); urlConnection.setUseCaches(false); urlConnection.setInstanceFollowRedirects(true); urlConnection.connect(); OutputStream os = urlConnection.getOutputStream(); bufer= null; os.write(message); os.flush(); os.close(); os = null; String encoding = urlConnection.getContentEncoding(); if (null == encoding || encoding.length() <1) encoding = "utf-8"; InputStream is = urlConnection.getInputStream(); int totalLen = urlConnection.getContentLength(); byte[] tmp = new byte[7 * 1024]; byte[] resultData = null; if(totalLen > 0) { ByteBuffer byBuf = ByteBuffer.allocate(totalLen); int len = 0; while ((len = is.read(tmp)) != -1) byBuf.put(tmp, 0, len); resultData = byBuf.array(); }else{ ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len = 0; while ((len = is.read(tmp)) != -1) bos.write(tmp, 0, len); resultData = bos.toByteArray(); bos.reset(); bos.close(); } is.close(); byte[] data = resultData; int size = data.length; byte[] data2 = null; if(size % 16 !=0 ){ int multiple = ((size /16)+1)*16; data2 = new byte[multiple]; System.arraycopy(data, 0, data2, 0, size); data = data2; }else{ data = data2; } return new String(data); } catch (Exception e) { // Log.e("MainActivity", "获取用户id异常", e); } return ""; } public static String getHttps(String url1){ String result = null; try{ URL url = new URL(url1); SSLContext sslctxt = SSLContext.getInstance("TLS"); sslctxt.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom()); HttpsURLConnection conn = (HttpsURLConnection)url.openConnection(); conn.setSSLSocketFactory(sslctxt.getSocketFactory()); conn.setHostnameVerifier(new MyHostnameVerifier()); conn.connect(); int respCode = conn.getResponseCode(); InputStream input = conn.getInputStream(); result = toString(input); System.out.println("------------------https result is :"+result); input.close(); conn.disconnect(); }catch(Exception e){ e.printStackTrace(); } return result; } private static String toString(InputStream input){ String content = null; try{ InputStreamReader ir = new InputStreamReader(input); BufferedReader br = new BufferedReader(ir); StringBuilder sbuff = new StringBuilder(); while(null != br){ String temp = br.readLine(); if(null == temp)break; sbuff.append(temp).append(System.getProperty("line.separator")); } content = sbuff.toString(); }catch(Exception e){ e.printStackTrace(); } return content; } static class MyX509TrustManager implements X509TrustManager{ @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if(null != chain){ for(int k=0; k < chain.length; k++){ X509Certificate cer = chain[k]; print(cer); } } } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { if(null != chain){ for(int k=0; k < chain.length; k++){ X509Certificate cer = chain[k]; print(cer); } } } @Override public X509Certificate[] getAcceptedIssuers() { return null; } private void print(X509Certificate cer){ int version = cer.getVersion(); String sinname = cer.getSigAlgName(); String type = cer.getType(); String algorname = cer.getPublicKey().getAlgorithm(); BigInteger serialnum = cer.getSerialNumber(); Principal principal = cer.getIssuerDN(); String principalname = principal.getName(); } } static class MyHostnameVerifier implements HostnameVerifier{ @Override public boolean verify(String hostname, SSLSession session) { return true; } } }说明:需要jar在附件中。
相关推荐
在Java开发中,中间接口转发(Middleware Interface Forwarding)是一种常见的设计模式,它主要用于实现业务逻辑的解耦和系统的稳定性。这个DEMO展示了如何在Java中构建这样的中间层,以应对第三方API可能出现的问题...
JAVA socket 端口转发,支持HTTP SOCKET。只是443 SSL加密。
本主题主要关注的是“Java串口转发”,即通过编程方式实现从一个串口读取数据并将其发送到另一个串口的过程。下面将详细介绍这个过程及相关知识点。 首先,串口通信的基础是了解串行通信协议,它是一种逐位传输数据...
java实现sysLog推送日志
JSch是一个纯Java实现的SSH2库,它提供了对SSH2协议的支持,包括文件传输、端口转发、图形SFTP客户端等功能。 在开发这样一个终端时,首先需要理解和配置JSch库。JSch库的核心类是`com.jcraft.jsch.Session`,这个...
JAVA 端口转发 端口映 射源码 jPortMap JAVA实现网络端口转发/端口映射功能
Java中Request请求转发是指在Servlet中使用RequestDispatcher将请求转发到另一个Servlet或JSP页面,以实现请求的重定向或包含。在本文中,我们将通过示例代码详细介绍Java中Request请求转发的实现过程。 ...
3. 测试代理:在开发测试中,可以通过Java实现数据包的转发,构建代理服务器,帮助测试跨域、负载均衡等功能。 4. 数据代理:在某些特殊场景下,比如内网穿透,Java抓包转发可以用于构建数据通道,使得内网资源可以...
在Java实现中,`SipApplicationDispatcher`类通常用于处理SIP事件,如请求发送、接收响应等。开发者需要实现相应的监听器接口(如`javax.sip.EventListener`)以处理这些事件。 在提供的压缩包文件`Sip_Java`中,...
通过这个Java实现的GB28181平台,开发者可以快速搭建符合GB28181标准的监控系统,实现视频流的接收、转发、存储和查询等功能。它可能还包含了设备注册、心跳检测、信令交互等关键模块。为了保证系统的稳定性和安全性...
在“WebRTC+Java实现多人视频通讯”的项目中,WebRTC主要负责前端的音视频采集、编码、传输和解码工作。用户可以在浏览器中直接参与视频通话,得益于WebRTC的API,开发者可以轻松获取用户的摄像头和麦克风权限,并...
综上所述,这个Java实现的HTTP服务器项目涵盖了Java网络编程、HTTP协议解析、反射、XML解析和多线程等多个核心知识点,是学习和实践这些技术的良好平台。通过对该项目的深入理解和实践,开发者可以提升在网络编程...
Java 实现TCP传输是网络...总的来说,Java实现TCP传输是网络编程的基础,理解和掌握这部分内容对于开发涉及网络通信的应用至关重要。通过不断的实践和学习,可以更好地应对各种网络编程场景,实现高效、稳定的TCP通信。
在"Netty数据转发工具"的场景中,描述提到的"Netty实现端口数据转发:3000进4000出"意味着通过Netty框架,我们可以构建一个服务器,将接收到的3000端口的数据转发到4000端口。这种数据转发功能在许多网络服务中都有...
本文将详细讲解如何在Servlet中实现请求转发以及用户登录验证。 首先,我们来理解请求转发(Request Forward)。在Servlet中,请求转发是一种在服务器内部将一个请求从一个资源传递到另一个资源的技术。这种方式是...
使用JavaMailSender包,结合Java8和springboot框架,使用公司阿里企业邮箱免费发送邮件,因为公司邮件不限数量,所以邮件测试发送无上限。对于QQ或163邮箱账户可能需要开通SMTP服务,具体信息请百度教程,有问题可以...
在Go中实现转发服务,我们需要关注以下几个核心概念和组件: 1. **HTTP服务器**:Go的标准库`net/http`提供了创建HTTP服务器的基础设施。通过实现`http.Handler`接口,我们可以定义处理HTTP请求的逻辑。例如,可以...
总之,Java实现SIP协议的关键在于理解SIP的基本概念,熟悉JSIP库的使用,以及如何处理SIP消息和会话。通过JSIP-0.8这样的库,开发者可以方便地构建功能丰富的SIP应用程序,实现VoIP通信、视频会议等多种功能。在实际...
Java实现HTTP PROXY是一个常见的需求,特别是在开发网络应用或者测试环境中,我们可能需要通过代理服务器转发HTTP请求。本文将深入探讨如何使用Java编程语言来创建一个HTTP代理服务器,并且会涉及相关的源码分析。 ...
本案例将详细讲解如何使用Java来实现企业微信的回调配置,并提供相关的工具代码示例。 1. **企业微信API介绍** 企业微信提供了丰富的API接口,包括但不限于用户管理、部门管理、消息推送等。回调配置主要是通过...