package com.ad.web.common;
import java.io.BufferedInputStream;
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.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import richinfo.rmapi.common.ApiConsts;
import richinfo.tools.Tools;
public class NetHelper {
private static int BUFFER_SIZE = 1024; // 缓冲区最大字节数
private static String LOG_MSG = "cmd=common:tools | method=NetHelper.";
private static final Logger log = Logger.getLogger(NetHelper.class);
/**
* 获取Ip地址,先取X-Forwarded-For地址,如果为空, <br>
* 取Proxy-Client-IP,如果为空,再取<br>
* WL-Proxy-Client-IP,如果为空,再取request.getRemoteAddr() <br>
* 注意:如果以上任何一种方式获取到的ip中有, 逗号分隔出的多个IP地址,则取第一个合法的IP地址(非unknown的地址)
*
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || "".equals(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || "".equals(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || "".equals(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip != null && !"".equals(ip)) {
String[] ips = ip.split(",");
for (int i = 0; i < ips.length; i++) {
if (ips[i] != null && !"".equals(ips[i])
&& !"unknown".equalsIgnoreCase(ips[i])) {
ip = ips[i];
break;
}
}
}
return ip;
}
/**
* 普通输入流转化为字节数组
*
* @param is
* @return
*/
public static byte[] getByteByStream(InputStream is) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
byte[] buf = new byte[BUFFER_SIZE];
int num;
while ((num = is.read(buf, 0, buf.length)) != -1) {
out.write(buf, 0, num);
}
out.close();
return out.toByteArray();
} catch (IOException e) {
return out.toByteArray();
} finally {
try {
if (out != null) {
out.close();
out = null;
}
} catch (IOException e) {
log.error("Exception", e);
}
}
}
/**
* 将流转成字符串
*
* @param is 输入流
* @return
*/
public static String getStringByStream(InputStream is) {
return getStringByStream(is, ConfigConst.DEFAULT_ENCODE);
}
/**
* 将流转成字符串
*
* @param is
* @param encode 指定编码
* @return
*/
public static String getStringByStream(InputStream is, String encode) {
byte[] bytes = getByteByStream(is);
return getStringByBytes(bytes, encode);
}
/**
* 将字节数组转成字符串
*
* @param bytes 字节数组
* @param encode 指定编码
* @return
*/
public static String getStringByBytes(byte[] bytes){
return getStringByBytes(bytes,ConfigConst.DEFAULT_ENCODE);
}
/**
* 将字节数组转成字符串
*
* @param bytes 字节数组
* @param encode 指定编码
* @return
*/
public static String getStringByBytes(byte[] bytes, String encode) {
if (bytes != null) {
try {
return new String(bytes, encode);
} catch (UnsupportedEncodingException e) {
log.debug("NetHelper.getStringByBytes is error. ", e);
}
}
return "";
}
/**
* GZIPInputStream 解压
*
* @param in
* @return
*/
private static byte[] unzip(InputStream in) {
GZIPInputStream gin = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
gin = new GZIPInputStream(in);
byte[] buf = new byte[BUFFER_SIZE];
int num;
while ((num = gin.read(buf, 0, buf.length)) != -1) {
out.write(buf, 0, num);
out.flush();
}
return out.toByteArray();
} catch (IOException e) {
return out.toByteArray();
} finally {
try {
if (out != null) {
out.close();
out = null;
}
} catch (IOException e) {
log.error(String.format("%s%s", LOG_MSG, "unzip"), e);
}
try {
if (gin != null) {
gin.close();
gin = null;
}
} catch (IOException e) {
log.error(String.format("%s%s", LOG_MSG, "unzip"), e);
}
}
}
public static void write(OutputStream out, InputStream is){
BufferedInputStream bis = null;
try {
byte[] buffer = new byte[BUFFER_SIZE];
bis = new BufferedInputStream(is);
int n = -1;
while ((n = bis.read(buffer,0,buffer.length)) != -1) {
out.write(buffer, 0, n);
out.flush();
}
} catch (Exception e) {
log.error(String.format("%s%s", LOG_MSG, "pipe"), e);
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
}
}
}
}
public static void write(OutputStream out, InputStream is, OutputStream rout){
BufferedInputStream bis = null;
try {
byte[] buffer = new byte[BUFFER_SIZE];
bis = new BufferedInputStream(is);
int n = -1;
while ((n = bis.read(buffer,0,buffer.length)) != -1) {
out.write(buffer, 0, n);
out.flush();
rout.write(buffer,0,n);
}
} catch (Exception e) {
log.error(String.format("%s%s", LOG_MSG, "pipe"), e);
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
}
}
}
}
/**
* post json格式的数据
* @param requestUrl
* @param data
* @param getReutrn
* @return
*/
public static String postJsonData(String requestUrl, String data,boolean getReutrn){
String sTotalString = "";
try{
URL url = new URL(requestUrl);
HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
httpconn.setConnectTimeout(ApiConsts.HTTP_CONN_TIMEOUT);
httpconn.setReadTimeout(ApiConsts.HTTP_READ_TIMEOUT);
httpconn.setDoInput(true);
httpconn.setDoOutput(true);
httpconn.setRequestMethod("POST");
httpconn.setRequestProperty("Accept", "text/javascript");
httpconn.setRequestProperty("Content-Type", "text/javascript; charset=" + CommonConst.APP_CHARSET);
//post json数据
OutputStreamWriter out = new OutputStreamWriter(httpconn.getOutputStream(), CommonConst.APP_CHARSET); // 指定编码
log.info(String.format("%s%s | req=%s | url=%s", LOG_MSG, "postjson",data,requestUrl));
out.append(data);
out.flush();
out.close();
InputStream inPs = httpconn.getInputStream();
if(getReutrn){
//得到返回结果
BufferedReader l_reader = new BufferedReader(new InputStreamReader(inPs));
String sCurrentLine="";
while ((sCurrentLine = l_reader.readLine()) != null) {
sTotalString += sCurrentLine + "\r\n";
}
return sTotalString;
}else{
return null;
}
}catch (Exception e) {
e.printStackTrace();
log.error(String.format("%s%s", LOG_MSG, "postjson"), e);
}
return null;
}
public static void main(String []msg){
String ip = "127.0.0.1,192.168.9.207,192.168.9.200";
if(Tools.isNotEmpty(ip)){
int pos = ip.indexOf(",");
if(pos>0){
ip = ip.substring(0, pos);
ip = ip.trim();
}
}
}
}
import java.io.BufferedInputStream;
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.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import richinfo.rmapi.common.ApiConsts;
import richinfo.tools.Tools;
public class NetHelper {
private static int BUFFER_SIZE = 1024; // 缓冲区最大字节数
private static String LOG_MSG = "cmd=common:tools | method=NetHelper.";
private static final Logger log = Logger.getLogger(NetHelper.class);
/**
* 获取Ip地址,先取X-Forwarded-For地址,如果为空, <br>
* 取Proxy-Client-IP,如果为空,再取<br>
* WL-Proxy-Client-IP,如果为空,再取request.getRemoteAddr() <br>
* 注意:如果以上任何一种方式获取到的ip中有, 逗号分隔出的多个IP地址,则取第一个合法的IP地址(非unknown的地址)
*
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || "".equals(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || "".equals(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || "".equals(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip != null && !"".equals(ip)) {
String[] ips = ip.split(",");
for (int i = 0; i < ips.length; i++) {
if (ips[i] != null && !"".equals(ips[i])
&& !"unknown".equalsIgnoreCase(ips[i])) {
ip = ips[i];
break;
}
}
}
return ip;
}
/**
* 普通输入流转化为字节数组
*
* @param is
* @return
*/
public static byte[] getByteByStream(InputStream is) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
byte[] buf = new byte[BUFFER_SIZE];
int num;
while ((num = is.read(buf, 0, buf.length)) != -1) {
out.write(buf, 0, num);
}
out.close();
return out.toByteArray();
} catch (IOException e) {
return out.toByteArray();
} finally {
try {
if (out != null) {
out.close();
out = null;
}
} catch (IOException e) {
log.error("Exception", e);
}
}
}
/**
* 将流转成字符串
*
* @param is 输入流
* @return
*/
public static String getStringByStream(InputStream is) {
return getStringByStream(is, ConfigConst.DEFAULT_ENCODE);
}
/**
* 将流转成字符串
*
* @param is
* @param encode 指定编码
* @return
*/
public static String getStringByStream(InputStream is, String encode) {
byte[] bytes = getByteByStream(is);
return getStringByBytes(bytes, encode);
}
/**
* 将字节数组转成字符串
*
* @param bytes 字节数组
* @param encode 指定编码
* @return
*/
public static String getStringByBytes(byte[] bytes){
return getStringByBytes(bytes,ConfigConst.DEFAULT_ENCODE);
}
/**
* 将字节数组转成字符串
*
* @param bytes 字节数组
* @param encode 指定编码
* @return
*/
public static String getStringByBytes(byte[] bytes, String encode) {
if (bytes != null) {
try {
return new String(bytes, encode);
} catch (UnsupportedEncodingException e) {
log.debug("NetHelper.getStringByBytes is error. ", e);
}
}
return "";
}
/**
* GZIPInputStream 解压
*
* @param in
* @return
*/
private static byte[] unzip(InputStream in) {
GZIPInputStream gin = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
gin = new GZIPInputStream(in);
byte[] buf = new byte[BUFFER_SIZE];
int num;
while ((num = gin.read(buf, 0, buf.length)) != -1) {
out.write(buf, 0, num);
out.flush();
}
return out.toByteArray();
} catch (IOException e) {
return out.toByteArray();
} finally {
try {
if (out != null) {
out.close();
out = null;
}
} catch (IOException e) {
log.error(String.format("%s%s", LOG_MSG, "unzip"), e);
}
try {
if (gin != null) {
gin.close();
gin = null;
}
} catch (IOException e) {
log.error(String.format("%s%s", LOG_MSG, "unzip"), e);
}
}
}
public static void write(OutputStream out, InputStream is){
BufferedInputStream bis = null;
try {
byte[] buffer = new byte[BUFFER_SIZE];
bis = new BufferedInputStream(is);
int n = -1;
while ((n = bis.read(buffer,0,buffer.length)) != -1) {
out.write(buffer, 0, n);
out.flush();
}
} catch (Exception e) {
log.error(String.format("%s%s", LOG_MSG, "pipe"), e);
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
}
}
}
}
public static void write(OutputStream out, InputStream is, OutputStream rout){
BufferedInputStream bis = null;
try {
byte[] buffer = new byte[BUFFER_SIZE];
bis = new BufferedInputStream(is);
int n = -1;
while ((n = bis.read(buffer,0,buffer.length)) != -1) {
out.write(buffer, 0, n);
out.flush();
rout.write(buffer,0,n);
}
} catch (Exception e) {
log.error(String.format("%s%s", LOG_MSG, "pipe"), e);
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
}
}
}
}
/**
* post json格式的数据
* @param requestUrl
* @param data
* @param getReutrn
* @return
*/
public static String postJsonData(String requestUrl, String data,boolean getReutrn){
String sTotalString = "";
try{
URL url = new URL(requestUrl);
HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
httpconn.setConnectTimeout(ApiConsts.HTTP_CONN_TIMEOUT);
httpconn.setReadTimeout(ApiConsts.HTTP_READ_TIMEOUT);
httpconn.setDoInput(true);
httpconn.setDoOutput(true);
httpconn.setRequestMethod("POST");
httpconn.setRequestProperty("Accept", "text/javascript");
httpconn.setRequestProperty("Content-Type", "text/javascript; charset=" + CommonConst.APP_CHARSET);
//post json数据
OutputStreamWriter out = new OutputStreamWriter(httpconn.getOutputStream(), CommonConst.APP_CHARSET); // 指定编码
log.info(String.format("%s%s | req=%s | url=%s", LOG_MSG, "postjson",data,requestUrl));
out.append(data);
out.flush();
out.close();
InputStream inPs = httpconn.getInputStream();
if(getReutrn){
//得到返回结果
BufferedReader l_reader = new BufferedReader(new InputStreamReader(inPs));
String sCurrentLine="";
while ((sCurrentLine = l_reader.readLine()) != null) {
sTotalString += sCurrentLine + "\r\n";
}
return sTotalString;
}else{
return null;
}
}catch (Exception e) {
e.printStackTrace();
log.error(String.format("%s%s", LOG_MSG, "postjson"), e);
}
return null;
}
public static void main(String []msg){
String ip = "127.0.0.1,192.168.9.207,192.168.9.200";
if(Tools.isNotEmpty(ip)){
int pos = ip.indexOf(",");
if(pos>0){
ip = ip.substring(0, pos);
ip = ip.trim();
}
}
}
}