http获取输入流输出流的参数及方法

这是一个Java工具类,用于处理HTTP GET和POST请求,获取输入流和输出流。包含获取请求参数、远程IP、User-Agent的方法,支持判断是否为Ajax或app-client请求,以及对URL编码。同时,提供从输入流读取数据的辅助功能,并处理session管理和cookie。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package project.property.web.utils;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import net.sf.json.JSONObject;


import org.apache.jda.core.orm.common.General;
import org.apache.log4j.Logger;


import project.property.common.EnvInfo;
import project.property.common.SessionInfo;
import project.property.sys.modal.TEnterpriseUsersModal;


/**
 * 处理 用户请求 sessioin 
 * request
 * response 的帮助类
 * @author kf04
 *
 */
public class HttpUtils {


private static final int YEAR = 60 * 60 * 24 * 365;
// ajax的请求头
public static final String AJAX_REQ = "X-Requested-With";
//ajax的请求标记值
public static final String AJAX_VAL = "XMLHttpRequest";

    private static String HTTP_CLIENT_TAG ="HTTP_CLIENT";

private static String HTTP_CLIENT_V ="T";

private static Logger log = Logger.getLogger(HttpUtils.class);

public static double getParameterDouble(HttpServletRequest request,
String name) {
String value = request.getParameter(name);


return (value == null || "".equals(value) ? 0 : Double
.parseDouble(value));
}


public static int getParameterInt(HttpServletRequest request, String name) {
String value = request.getParameter(name);


return (value == null || "".equals(value) ? 0 : Integer.parseInt(value));
}


public static String getParameterString(HttpServletRequest request,
String name) {
String value = request.getParameter(name);


return (value == null ? "" : value);
}


public static String getRemortIP(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}


public static String getUserAgent(HttpServletRequest request) {
String agent = request.getHeader("User-Agent");
return agent != null ? agent : "";
}


public static String appendUserAgent(HttpServletRequest request,
String content) {
return content + "\r\n | User Agent: " + getUserAgent(request);
}

/**
* 判断请求是否为app-client的请求
* @param request
* @return
*/
public static boolean isHttpClientReq(HttpServletRequest request){
String header = request.getHeader(HTTP_CLIENT_TAG);
return HTTP_CLIENT_V.equals(header);
}

/**
* 判断请求是否为ajax请求
* @param request
* @return
*/
public static boolean isAjaxReq(HttpServletRequest request){
String ajax = request.getHeader(AJAX_REQ);
return AJAX_VAL.equals(ajax);
}

/**
* 对url进行编码

* @param url
* @param enc
* @return
* @throws UnsupportedEncodingException
*/
public static String encodeUrl(String url, String enc)
throws UnsupportedEncodingException {
return URLEncoder.encode(url, enc);
}


/**
* 从HTTP请求中获取输入流

* @param requestUrl
* @param requestMethod
* @return
* @throws IOException
*/
public static String doHttpGetRequest(String requestUrl) throws IOException {
HttpURLConnection httpConnection = null;
try {
// String strTemp=null;
URL url = new URL(requestUrl);
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
return readInputStreamAsString(inputStream,
httpConnection.getContentLength());
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
}
}
}


/**
* 从HTTP请求中获取输入流

* @param requestUrl
* @param requestMethod
* @return
* @throws IOException
*/
public static String doHttpPostRequest(String requestUrl,
String requestContent) throws IOException {
HttpURLConnection httpConnection = null;
try {
// String strTemp=null;
URL url = new URL(requestUrl);
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("POST");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setDefaultUseCaches(false);
httpConnection.setDefaultUseCaches(false);
OutputStreamWriter outStreamWriter = new OutputStreamWriter(
httpConnection.getOutputStream());
outStreamWriter.write(requestContent);
outStreamWriter.flush();
outStreamWriter.close();
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
return readInputStreamAsString(inputStream,
httpConnection.getContentLength());
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
}
}
}


/**
* 从输入流中读取数据

* @param tInputStream
* @return
* @throws IOException
*/
public static String readInputStreamAsString(InputStream inputStream,
int length) throws IOException {
if (inputStream != null) {
byte[] streamBytes = new byte[length];
inputStream.read(streamBytes);
return new String(streamBytes, "UTF-8");
}
return null;
}


/**
* 获取用户当前的session

* @param req
* @return
*/
public static String getSessionId(HttpServletRequest req) {
return req.getSession().getId();
}


/**
* 从当前的session中获取用户相关的值

* @param req
* @return
*/
public static Object getFromSession(HttpServletRequest req,String key) {
return req.getSession().getAttribute(key);
}

/**
* 从当前的session中获取用户相关的值

* @param req
* @return
*/
public static void removeFromSession(HttpServletRequest req,String key) {
req.getSession().removeAttribute(key);
}

//设置env到cookie中
public static void setValToCookie(HttpServletRequest request,HttpServletResponse response,String key,String value){
String base = (String)request.getSession().getAttribute(WebConstants.BASE_PATH);
base = base.replaceAll("/", "_");
General.addCookie(response, "/", base.concat(key), value);
}

public static String getValFromCookie(HttpServletRequest request,String key){
String rlt ="";
String base = (String)request.getSession().getAttribute(WebConstants.BASE_PATH);
base = base.replaceAll("/", "_");
rlt = General.getCookie(request, base.concat(key));
return rlt;
}

/**
* 设置值到当前的session中

* @param req
* @return
*/
public static void setToSession(HttpServletRequest req,String key,Object value) {
req.getSession().setAttribute(key,value);
}



/**
* 获取sessioninfo信息
* @param req  
* @return
* @throws Exception 
*/
public static SessionInfo getSessionInfo(HttpServletRequest req) {
HttpSession session = req.getSession();
SessionInfo  si =(SessionInfo)session.getAttribute(SessionInfo.SESSION_TAG);
if(null == si){
si = new SessionInfo();
//si.setEnv(createEnvFromReq(req));
//si.setAuthInfo(createAuthFromReq(req));
try {
String opCode = "OTO";
String mcCode = "SG";
/* SysOrgOpIntf orgIntf;
orgIntf = (SysOrgOpIntf)ImplementorFactory.getImplemetator(SysOrgOpIntf.class, "SysOpIntf");
VariantHolder<SysOrgOpModal> vop = new VariantHolder<SysOrgOpModal>();*/
/*orgIntf.get(Constants.UnknownID, opCode, vop);*/
/* SysOrgMcIntf orgMcIntf = (SysOrgMcIntf)ImplementorFactory.getImplemetator(SysOrgMcIntf.class, "SysMcIntf");
VariantHolder<SysOrgMcModal> vmc = new VariantHolder<SysOrgMcModal>();
orgMcIntf.get(vop.value.getSYS_ORG_ID(), mcCode, vmc);*/
//si.setSysOpInfo(vop.value);
//si.setSysMcInfo(vmc.value);
TEnterpriseUsersModal am=new TEnterpriseUsersModal();
si.setAuthInfo(am);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.setAttribute(SessionInfo.SESSION_TAG, si);
session.setAttribute(WebConstants.BASE_PATH, "");
session.setAttribute(SessionInfo.SESSION_TAG,si);
}
return si;
}


private static EnvInfo createEnvFromReq(HttpServletRequest req){
EnvInfo env = new EnvInfo();
//env.setHardwarePlatform(HardwarePlatformType.PC);
//env.setSysPlatform(SysPlatformType.BROWSE);
return env;
}

/* private static AuthModal createAuthFromReq(HttpServletRequest req){
AuthModal auth = new AuthModal();
//auth.setSYS_OP_ID(WebConstants.OP_ID);
//auth.setSYS_MC_ID(WebConstants.MC_ID);
//auth.setSYS_IS_ID(WebConstants.IS_ID);
//auth.setSYS_DP_ID(WebConstants.DP_ID);
//auth.setPRSNL_ID(Constants.UnknownID);
return auth;
}*/

/**
* 判断请求是否要设置组织机构信息
* orgCode不同或者sessionInf为null

* @param req
* @param code
* @return
*/
public static boolean needSeSessionInfo(HttpServletRequest req) {
HttpSession session = req.getSession();
String wccode = req.getParameter("code");
String refresh = req.getParameter("refresh");
String pfkey =  req.getParameter("pfkey");
SessionInfo  si =(SessionInfo)session.getAttribute(SessionInfo.SESSION_TAG);
//如果请求参数包括微信的授权认证code需要重新登录 或者 refresh参数需要刷新
if(((null == si || !si.isIsAuth()) && !General.isEmpty(wccode)) || !General.isEmpty(refresh)){
session.removeAttribute(SessionInfo.SESSION_TAG);
log.info(String.format("====================refresh session by code:%s,refresh:%s,pfkey:%s",wccode,refresh,pfkey));
return true;
}

return null == si||null==si.getAuthInfo();
}


/**
* 返回操作错误的json给客户端
* @param msg
* @param errorCode
* @return
*/
public static String jsonErrorMsg(String msg,String errorCode){
JSONObject jo = JSONObject.fromObject("{}");
jo.element("error", errorCode);
jo.element("msg", msg);
return jo.toString();
}

/**
* 返回操作正确的msg给客户端
* @return
*/
public static String jsonSuccessMsg(){
JSONObject jo = JSONObject.fromObject("{}");
jo.element("success", "true");
return jo.toString();
}
/**
* 获取验证码
* @return
*/
public static String getAuthCode(HttpServletRequest request){
return (String)request.getSession().getAttribute(WebConstants.AUTH_CODE_TAG);
}
/**
* 设置验证码
* @param request
* @param code
*/
public static void setAuthCode(HttpServletRequest request,String code){
HttpSession session = request.getSession(true);
session.setAttribute(WebConstants.AUTH_CODE_TAG, code);
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值