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

Java Http请求发送工具

2017-01-24 00:00 411 查看
package com.yss.framework.protocol.http;

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.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Vector;

import com.yss.framework.api.common.YssConstant;
import com.yss.framework.api.context.AppContext;
import com.yss.framework.api.context.LoggingInfo;
import com.yss.framework.api.context.YssContextFactory;
import com.yss.framework.api.exception.YssRuntimeException;
import com.yss.framework.api.exception.pojo.TransferErrorMessage;
import com.yss.framework.api.logger.LogManager;
import com.yss.framework.api.logger.Logger;
import com.yss.framework.api.mvc.control.ControlException;
import com.yss.framework.api.service.ServiceException;
import com.yss.framework.api.util.JsonUtil;
import com.yss.framework.api.util.StringUtil;
import com.yss.framework.api.util.YssCons;
import com.yss.framework.context.ContextFactory;
import com.yss.framework.exception.TransferException;

/**
* HTTP请求对象
*
* @author YYmmiinngg
*/
public class HttpRequester {
private Logger logger = LogManager.getLogger(this.getClass());
private String defaultContentEncoding;

public HttpRequester() {
this.defaultContentEncoding = "UTF-8";
}

/**
* 发送GET请求
*
* @param urlString
*            URL地址
* @return 响应对象
* @throws IOException
*/
public HttpResponse sendGet(String urlString) throws Exception {
return this.send(urlString, "GET", null, null,70000000);
}

/**
* 发送GET请求
*
* @param urlString
*            URL地址
* @param params
*            参数集合
* @return 响应对象
* @throws IOException
*/
public HttpResponse sendGet(String urlString, Map<String, String> params)
throws Exception {
return this.send(urlString, "GET", params, null,70000000);
}

/**
* 发送GET请求
*
* @param urlString
*            URL地址
* @param params
*            参数集合
* @param propertys
*            请求属性
* @return 响应对象
* @throws IOException
*/
public HttpResponse sendGet(String urlString, Map<String, String> params,
Map<String, String> propertys) throws Exception {
return this.send(urlString, "GET", params, propertys,70000000);
}

/**
* 发送POST请求
*
* @param urlString
*            URL地址
* @return 响应对象
* @throws IOException
*/
public HttpResponse sendPost(String urlString) throws Exception {
return this.send(urlString, "POST", null, null,70000000);
}

/**
* 发送POST请求
*
* @param urlString
*            URL地址
* @param params
*            参数集合
* @return 响应对象
* @throws IOException
*/
public HttpResponse sendPost(String urlString, Map<String, String> params)
throws Exception {
return this.send(urlString, "POST", params, null,70000000);
}

public HttpResponse sendPost(String urlString, Map<String, String> params,int timeout)
throws Exception {
return this.send(urlString, "POST", params, null,timeout);
}

/**
* 发送POST请求
*
* @param urlString
*            URL地址
* @param params
*            参数集合
* @param propertys
*            请求属性
* @return 响应对象
* @throws IOException
*/
public HttpResponse sendPost(String urlString, Map<String, String> params,
Map<String, String> propertys) throws Exception {
return this.send(urlString, "POST", params, propertys,70000000);
}

/**
* 发送HTTP请求
*
* @param urlString
* @return 响映对象
* @throws IOException
*/
private HttpResponse send(String urlString, String method,
Map<String, String> parameters, Map<String, String> propertys,int timeout)
throws Exception {
HttpURLConnection urlConnection = null;
try{
if (method.equalsIgnoreCase("GET") && parameters != null) {
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : parameters.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(parameters.get(key));
i++;
}
urlString += param;
}
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setRequestMethod(method);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);

urlConnection.setConnectTimeout(timeout);
urlConnection.setReadTimeout(timeout);

// 添加用户请求信息到头中
this.setContextToRequest(urlConnection);

if (propertys != null)
for (String key : propertys.keySet()) {
urlConnection.addRequestProperty(key, propertys.get(key));
}

if (method.equalsIgnoreCase("POST") && parameters != null) {
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : parameters.keySet()) {
if (i != 0)
param.append("&");
param.append(key).append("=").append(parameters.get(key));
i++;
}

//urlConnection.getOutputStream()会隐式调用connect方法,所以注掉下面一行
//urlConnection.connect();
OutputStream os = urlConnection.getOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(os, defaultContentEncoding);
ow.write(param.toString());
ow.flush();
os.close();
ow.close();
}
return this.makeContent(urlString, urlConnection);
}catch(Exception e){
String reqMsg = "RequestError url:" + urlString + "  methodName:"
+ method + " timeout:" + timeout;
logger.log(reqMsg);
if(e instanceof YssRuntimeException){
throw e;
}else{
throw  new ControlException(e);
}
}
}

/**
* 得到响应对象
*
* @param urlConnection
* @return 响应对象
* @throws IOException
*/
private HttpResponse makeContent(String urlString,
HttpURLConnection urlConnection) throws Exception {
HttpResponse httpResponser = new HttpResponse();
try {
InputStream in = urlConnection.getInputStream();

String ecod = urlConnection.getContentEncoding();
if (ecod == null) {
ecod = this.defaultContentEncoding;
}

BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in, ecod));
httpResponser.contentCollection = new Vector<String>();
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
httpResponser.contentCollection.add(line);
temp.append(line);
line = bufferedReader.readLine();
}
bufferedReader.close();

httpResponser.urlString = urlString;

httpResponser.defaultPort = urlConnection.getURL()
.getDefaultPort();
httpResponser.file = urlConnection.getURL().getFile();
httpResponser.host = urlConnection.getURL().getHost();
httpResponser.path = urlConnection.getURL().getPath();
httpResponser.port = urlConnection.getURL().getPort();
httpResponser.protocol = urlConnection.getURL().getProtocol();
httpResponser.query = urlConnection.getURL().getQuery();
httpResponser.ref = urlConnection.getURL().getRef();
httpResponser.userInfo = urlConnection.getURL().getUserInfo();

boolean isError = false;
isError = (urlConnection.getHeaderField(YssCons.ERROR_TO_CLIENT) == null? false:urlConnection.getHeaderField(YssCons.ERROR_TO_CLIENT).equalsIgnoreCase("error"));
if(isError){
line = StringUtil.uncompress(temp.toString());

/**
* Author : ChenLong
* Date   : 2014-09-03
* Status : Add
* Comment: 异常信息处理
*/
TransferErrorMessage transErrorMess = JsonUtil.toBean(line, TransferErrorMessage.class);
TransferException transferException = new TransferException();
transferException.build(transErrorMess);
throw new ServiceException(transferException);

//					TransDataObj obj = JsonUtil.toBean(line, TransDataObj.class);
//					throw new TransferException(obj.getRetValue());
}

httpResponser.content = temp.toString();

httpResponser.contentEncoding = ecod;
httpResponser.code = urlConnection.getResponseCode();
httpResponser.message = urlConnection.getResponseMessage();
httpResponser.contentType = urlConnection.getContentType();
httpResponser.method = urlConnection.getRequestMethod();
httpResponser.connectTimeout = urlConnection
.getConnectTimeout();
httpResponser.readTimeout = urlConnection.getReadTimeout();
in.close();

return httpResponser;

} catch (Exception e) {
String resMsg = "ResponseError readTimeout:"
+ httpResponser.readTimeout
+ " connectTimeout:"
+ httpResponser.connectTimeout
+ " contentLen:"
+ (httpResponser.content != null ? httpResponser.content
.length() : 0) + " url:" + httpResponser.urlString
+ " port:" + httpResponser.defaultPort + " host:"
+ httpResponser.host + " userInfo:"
+ httpResponser.userInfo;
logger.log(resMsg);
if(e instanceof YssRuntimeException){
throw e;
}else{
throw  new ControlException(e);
}
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}

/**
* 默认的响应字符集
*/
public String getDefaultContentEncoding() {
return this.defaultContentEncoding;
}

/**
* 设置默认的响应字符集
*/
public void setDefaultContentEncoding(String defaultContentEncoding) {
this.defaultContentEncoding = defaultContentEncoding;
}

public HttpResponse send(String message, String urlString) throws Exception {
return this.send(message, urlString, 70000000);
}

/**
* 发送HTTP请求,直接发送信息,而不是参数或者属性
*
* @param urlString
* @return 响映对象
* @throws IOException
*/
public HttpResponse send(String message, String urlString,int timeout) throws Exception {

HttpURLConnection urlConnection = null;
try{
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-type",
"application/x-java-serialized-object");

urlConnection.setConnectTimeout(timeout);
urlConnection.setReadTimeout(timeout);

// 添加用户请求信息到头中
this.setContextToRequest(urlConnection);

OutputStream os = urlConnection.getOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(os, defaultContentEncoding);
ow.write(message);
ow.flush();
os.close();
ow.close();

return this.makeContent(urlString, urlConnection);
}catch(Exception e){
String reqMsg = "RequestError url:" + urlString + "  contextLen:"
+ (message != null ? message.length() : 0) + " timeout:"
+ timeout;
logger.log(reqMsg);
if(e instanceof YssRuntimeException){
throw e;
}else{
throw  new ControlException(e);
}
}
}

public HttpResponse sendByte(String message, String urlString) throws Exception {
return this.sendByte(message, urlString, 70000000);
}

/**
* 发送HTTP请求,直接发送信息,而不是参数或者属性
*
* @param urlString
* @return 响映对象
* @throws IOException
*/
public HttpResponse sendByte(String message, String urlString,int timeout)
throws Exception {

HttpURLConnection urlConnection = null;
try{
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-type",
"application/x-java-serialized-object");

urlConnection.setConnectTimeout(timeout);
urlConnection.setReadTimeout(timeout);

// 添加用户请求信息到头中
this.setContextToRequest(urlConnection);

OutputStream os = urlConnection.getOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(os, "UTF-8");
ow.write(message);
ow.flush();
os.close();
ow.close();

return this.makeContent(urlString, urlConnection);
}catch(Exception e){
String reqMsg = "RequestError url:" + urlString + "  contextLen:"
+ (message != null ? message.length() : 0) + " timeout:"
+ timeout;
logger.log(reqMsg);
if(e instanceof YssRuntimeException){
throw e;
}else{
throw  new ControlException(e);
}
}
}

/**
* 将当前应用的用户请求信息写到http请求头中远程传递
*
* @param conn
*/
private void setContextToRequest(HttpURLConnection conn) {
boolean isOSGI = YssContextFactory.getInstance().getOSGI();
LoggingInfo info = null;
if(isOSGI) {
info = YssContextFactory.getInstance().getLogInfo();
} else {
AppContext context = (AppContext) ContextFactory.getContext();
info = context.getLogInfo();
}

String str = JsonUtil.toString(info);

/* author : ChenLong
* date   : 2013-08-14
* comment: 解决乱码
* */
try {
str = new String(str.getBytes("ISO-8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
logger.log("将字符串编码转发成UTF-8失败:", e);
}
conn.addRequestProperty(YssConstant.CUS_HTTP_HEADER_LOGININFO, str);

//Orlando 20130709 因为服务器的安全设置不接受Java程序作为客户端访问,导致java.io.IOException: Server returned HTTP response code: 500 for URL错误,解决方案是设置客户端的User Agent
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: