一、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在附件中。