您的位置:首页 > 理论基础 > 计算机网络

转发请求实现HttpURLConnection

2017-05-26 14:57 781 查看
因为项目将用户请求转发到其他项目中,使用response重定向请求可以成功发送但是如果转发请求使用request不能实现,找了点资料自己实现一个转发类,下面是实现代码:

package com.httpproxy.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.httpproxy.enums.APIState;
import com.httpproxy.model.APIMsgModel;
import com.httpproxy.model.ModelXML;
import com.httpproxy.tool.PP;
import com.httpproxy.tool.UtilMap;
import com.httpproxy.tool.UtilProxy;

/**
* 请求转发代理类
*
*/
public class HttpProxy extends HttpServlet {
private static final Logger log = Logger.getLogger(HttpProxy.class);
private static final long serialVersionUID = 1L;
private UtilProxy util = new UtilProxy();

/**
* Default constructor.
*/
public HttpProxy() {
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException {
request.setCharacterEncoding(PP.GP("CharacterEncoding"));
long startTime = System.nanoTime();
Map<String, ModelXML> map = UtilMap.get().getMap();
// 获取访问接口名称+方法
String path = request.getServletPath();
ModelXML xml = (ModelXML) map.get(path);
if (xml != null) {
PrintWriter out = response.getWriter();
String result = null;
try {
if (xml.getType() == 1) {
// 获取参数
StringBuffer parameterBuffer = paermap(request);

// 打印输入参数
if (Boolean.parseBoolean(PP.GP("API.InParam"))) {
HashMap<String, Object> headerMap = new HashMap<String, Object>();
Enumeration<String> hears = request.getHeaderNames();
while (hears.hasMoreElements()) {
String key = hears.nextElement();
String value = request.getHeader(key);
headerMap.put(key, value);

}
log.info(Thread.currentThread().getName() + "-" + path
+ "头部信息:" + JSON.toJSONString(headerMap)
+ "输入参数:" + parameterBuffer);
}
result = util.proUrl(request, xml.getInnerurl(),
parameterBuffer);
out.write(result);

return;
} else if (xml.getType() == 0) {
result = xml.getNeturl();
result = JSON.toJSONString(new APIMsgModel(APIState.S307,
"重定向目标服务器", result));
out.write(result);
return;
}
} catch (Exception e) {
log.error(Thread.currentThread().getName() + "-" + path, e);
out.write(JSON.toJSONString(new APIMsgModel(APIState.S500,
"代理服务器故障")));
} finally {
out.flush();
out.close();
// 打印输出参数
if (Boolean.parseBoolean(PP.GP("API.OutParam"))) {
log.info(Thread.currentThread().getName() + "-" + path
+ "输出参数:" + result);
}
// 打印执行时间
if (Boolean.parseBoolean(PP.GP("API.Time"))) {
BigDecimal consumingTime = BigDecimal.valueOf(
System.nanoTime() - startTime).divide(
BigDecimal.valueOf(1000000000));// /1000000000
log.info(Thread.currentThread().getName() + "-" + path
+ "执行时间:" + consumingTime.doubleValue() + "秒");
}
}
} else {
response.setStatus(404);
return;
}
}

/**
* 获取参数
*
* @param request
* @return
* @throws Exception
*/
private StringBuffer paermap(HttpServletRequest request) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(
request.getInputStream(), PP.GP("CharacterEncoding")));
String par = "";
StringBuffer paer = new StringBuffer();
while ((par = in.readLine()) != null) {
paer.append(par);
}
return paer;
}
}


访问实现代码:

package com.httpproxy.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

/**
* 转发帮助类
*
* @time 2016年8月3日 下午12:50:49
*/
public class UtilProxy {
// 设置连接超时时间(单位毫秒)
private Integer connectTimeout = 100000;
// 设置读数据超时时间(单位毫秒)
private Integer socketTimeout = 100000;
private String proxyHost = null;
private Integer proxyPort = null;

pu
a228
blic String proUrl(HttpServletRequest request, String url,
StringBuffer parameterBuffer) throws Exception {
URL localURL = new URL(url);
URLConnection connection = openConnection(localURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

// 获取请求方式
String method = request.getMethod();
// 获取请求头部信息
Enumeration<String> hears = request.getHeaderNames();
while (hears.hasMoreElements()) {
String key = hears.nextElement();
String value = request.getHeader(key);
if (key.equals("content-type") && value == null) {
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
} else {
httpURLConnection.setRequestProperty(key, value);
}
}

httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod(method);
httpURLConnection.setRequestProperty("Accept-Charset",
PP.GP("CharacterEncoding"));
httpURLConnection.setInstanceFollowRedirects(true);
renderRequest(httpURLConnection);
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;

try {
if (method.endsWith("POST")) {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream,
PP.GP("CharacterEncoding"));
outputStreamWriter.write(parameterBuffer.toString());
outputStreamWriter.flush();
}
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is "
+ httpURLConnection.getResponseCode());
}
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream,
PP.GP("CharacterEncoding"));
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}

} catch (Exception e) {
throw new Exception(e);
} finally {

if (outputStreamWriter != null) {
outputStreamWriter.close();
}

if (outputStream != null) {
outputStream.close();
}

if (reader != null) {
reader.close();
}

if (inputStreamReader != null) {
inputStreamReader.close();
}

if (inputStream != null) {
inputStream.close();
}

}
// System.out.println(resultBuffer.toString());
return resultBuffer.toString();
}

/**
* 创建连接
*
* @param localURL
* @return
* @throws IOException
*/
private URLConnection openConnection(URL localURL) throws IOException {
URLConnection connection;
if (proxyHost != null && proxyPort != null) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
proxyHost, proxyPort));
connection = localURL.openConnection(proxy);
} else {
connection = localURL.openConnection();
}
return connection;
}

/**
* 设置请求超时时间
*
* @param connection
*/
private void renderRequest(URLConnection connection) {

if (connectTimeout != null) {
connection.setConnectTimeout(connectTimeout);
}

if (socketTimeout != null) {
connection.setReadTimeout(socketTimeout);
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: