已有工具类:
1、MD5工具类
2、base64工具类
3、图片处理工具类
4、压缩解压工具类
5、Http工具类
6、其他工具类(杂类)
一般Java工具类
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;
import java.util.UUID;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils {
/**
* 读文本文件
*
* @param file 文件
* @return 文本内容
*/
public static String file2String(File file) {
StringBuilder result = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
String s = null;
while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行
result.append((result.length() == 0 ? "" : System.lineSeparator()) + s);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
/**
* 写文本文件
*
* @param str 文本
* @param file 文件
* @return 写出是否成功
*/
public static boolean string2File(String str, File file) {
try {
FileOutputStream fos;
fos = new FileOutputStream(file);
fos.write(str.getBytes());
fos.flush();
fos.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 取两个文本之间的文本值
*
* @param text
* @param left
* @param right
* @return
*/
public static String getSubString(String text, String left, String right) {
String result = "";
int zLen;
if (left == null || left.isEmpty()) {
zLen = 0;
} else {
zLen = text.indexOf(left);
if (zLen > -1) {
zLen += left.length();
} else {
zLen = 0;
}
}
int yLen = text.indexOf(right, zLen);
if (yLen < 0 || right == null || right.isEmpty()) {
yLen = text.length();
}
result = text.substring(zLen, yLen);
return result;
}
/**
* 判断字符串中是否包含中文
*
* @param str 待校验字符串
* @return 是否为中文
* @warn 不能校验是否为中文标点符号
*/
public static boolean isContainChinese(String str) {
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}
/**
* 毫秒转化时分秒毫秒
*
* @param s
* @return
*/
public static String formatTime(Long s) {
Integer mi = 60;
Integer hh = mi * 60;
Integer dd = hh * 24;
Long day = s / dd;
Long hour = (s - day * dd) / hh;
Long minute = (s - day * dd - hour * hh) / mi;
Long second = s - day * dd - hour * hh - minute * mi;
StringBuffer sb = new StringBuffer();
if (day > 0) {
sb.append(day + "天");
}
if (hour > 0) {
sb.append(hour + "小时");
}
if (minute > 0) {
sb.append(minute + "分");
}
if (second > 0) {
sb.append(second + "秒");
}
return sb.toString();
}
/**
* 获取机器码
*
* @return 获取失败返回null
*/
public static String getMachineCode() {
Preferences pre = Preferences.userRoot().node("/cmbb_desktop");
try {
if (pre.nodeExists("/")) {
String code = pre.get("code", "");
if (code.equals("")) {
UUID uuid = UUID.randomUUID();
code = uuid.toString().replaceAll("-", "");
pre.put("code", code);
}
System.out.println("存在" + code);
return code;
} else {
UUID uuid = UUID.randomUUID();
String code = uuid.toString().replaceAll("-", "");
pre.put("code", code);
System.out.println("不存在" + code);
return code;
}
} catch (BackingStoreException e) {
e.printStackTrace();
}
return null;
}
/**
* 获得东八区时间
*
* @return
*/
public static String getChinaTime() {
TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(timeZone);
return simpleDateFormat.format(new Date());
}
/**
* 生成取值范围[最小值,最大值)内的整数
*
* @param min 最小值
* @param max 最大值
* @return 整数
*/
public static int random(int min, int max) {
float ret = (min + max) / 2;
if (min < max) {
Random rm = new Random();
ret = min + rm.nextFloat() * (max - min);
} else if (min == max) {
ret = min;
} else {
Random rm = new Random();
ret = max + rm.nextFloat() * (min - max);
}
return (int) ret;
}
/**
* 获取资源路径
*
* @return
*/
public static String getResourcesPath() {
String path = Utils.class.getClass().getResource("/").getPath();
path = path.substring(1, path.length());
try {
path = java.net.URLDecoder.decode(path, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return path;
}
/**
* 获取资源路径
*
* @param fileName
* @return
*/
public static String getResourcesPath(String fileName) {
String path = getResourcesPath();
return path + fileName;
}
/**
* 获取项目路径
*
* @return
*/
public static String getProjectPath() {
String path = System.getProperty("user.dir");
try {
path = java.net.URLDecoder.decode(path, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return path;
}
/**
* 增加加载库路径
*
* @param libraryPath
* @throws Exception
*/
public static void addLibraryDir(String libraryPath) throws Exception {
Field userPathsField = ClassLoader.class.getDeclaredField("usr_paths");
userPathsField.setAccessible(true);
String[] paths = (String[]) userPathsField.get(null);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < paths.length; i++) {
if (libraryPath.equals(paths[i])) {
continue;
}
sb.append(paths[i]).append(';');
}
sb.append(libraryPath);
System.setProperty("java.library.path", sb.toString());
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
}
}MD5工具类
public class MD5 {
// 首先初始化一个字符数组,用来存放每个16进制字符
private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* 获得一个字符串的MD5值
*
* @param input 输入的字符串
* @return 输入字符串的MD5值
*
*/
public static String md5(String input) {
if (input == null)
return null;
try {
// 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”)
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
// 输入的字符串转换成字节数组
byte[] inputByteArray = input.getBytes("utf-8");
// inputByteArray是输入字符串转换得到的字节数组
messageDigest.update(inputByteArray);
// 转换并返回结果,也是字节数组,包含16个元素
byte[] resultByteArray = messageDigest.digest();
// 字符数组转换成字符串返回
return byteArrayToHex(resultByteArray);
} catch (NoSuchAlgorithmException e) {
return null;
} catch (UnsupportedEncodingException e) {
return null;
}
}
/**
* 获取文件的MD5值
*
* @param file
* @return
*/
public static String md5(File file) {
try {
if (!file.isFile()) {
System.err.println("文件" + file.getAbsolutePath() + "不存在或者不是文件");
return null;
}
FileInputStream in = new FileInputStream(file);
String result = md5(in);
in.close();
return result;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String md5(InputStream in) {
try {
MessageDigest messagedigest = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read = 0;
while ((read = in.read(buffer)) != -1) {
messagedigest.update(buffer, 0, read);
}
in.close();
String result = byteArrayToHex(messagedigest.digest());
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String byteArrayToHex(byte[] byteArray) {
// new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))
char[] resultCharArray = new char[byteArray.length * 2];
// 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去
int index = 0;
for (byte b : byteArray) {
resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
resultCharArray[index++] = hexDigits[b & 0xf];
}
// 字符数组组合成字符串返回
return new String(resultCharArray);
}
}base64工具类
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* BASE64加密解密
*/
@SuppressWarnings("restriction")
public class Base64
{
/**
* BASE64解密
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
}
/**
* BASE64加密
* @param key
* @return
* @throws Exception
*/
public static String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
}图片处理工具类
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import cn.pixelsol.dm4j.dm.support.Rect;
public class ImageUtils {
/**
* 根据指定的宽高对{@link Image}图像进行绽放
* @param src 原图对象
* @param width 目标图像宽度
* @param height 目标图像高度
* @return 返回缩放后的{@link Image}对象
*/
public static Image resize(Image src, int width, int height) {
Image scaled = new Image(Display.getDefault(), width, height);
GC gc = new GC(scaled);
try{
gc.setAdvanced(true); // 打开高级绘图模式
gc.setAntialias(SWT.ON);// 设置消除锯齿
gc.setInterpolation(SWT.HIGH); // 设置插值
gc.drawImage(src, 0, 0, src.getBounds().width, src.getBounds().height,0, 0, width, height);
}finally{
gc.dispose();
}
return scaled;
}
/**
* 根据缩放比例对{@link Image}对象进行缩放
* @param src 原图对象
* @param zoom 缩放比例
* @return 返回缩放后的{@link Image}对象
*/
public static Image resize(Image src, float zoom) {
Rectangle bounds = src.getBounds();
bounds.width*=zoom;
bounds.height*=zoom;
return resize(src,bounds.width,bounds.height);
}
public static Image getImage(String path) {
Image image = new Image(Display.getCurrent(), path);
return image;
}
public static Image getImage(byte[] bmp) {
InputStream buffin = new ByteArrayInputStream(bmp);
Image image = new Image(Display.getCurrent(), buffin);
return image;
}
public static Image getImage(String path, int width, int height) {
Image image = resize(getImage(path), width, height);
return image;
}
public static Image getImage(byte[] bmp, int width, int height) {
Image image = resize(getImage(bmp), width, height);
return image;
}
public static Rect getImageRect(String path) {
return new Rect(0, 0, getImage(path).getBounds().width, getImage(path).getBounds().height);
}
public static void drawRectOnPic(String src_pic, String tar_pic, Color color, List<Rect> rect_list) throws IOException {
InputStream in = new FileInputStream(src_pic);//图片路径
BufferedImage image = ImageIO.read(in);
Graphics g = image.getGraphics();
g.setColor(Color.YELLOW);//画笔颜色
for(Rect rect : rect_list) {
System.out.println("rect:" + rect);
g.drawRect(rect.getLeft(), rect.getTop(), rect.getWidth(), rect.getHeight());//矩形框(原点x坐标,原点y坐标,矩形的长,矩形的宽)
}
//g.dispose();
FileOutputStream out = new FileOutputStream(tar_pic);//输出图片的地址
ImageIO.write(image, "jpeg", out);
}
}压缩解压工具类
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import java.io.OutputStream;
import java.util.List;
/**
*
* @ClassName ZipUtils
* @Description Zip压缩工具类
* @author zwgu
* @date 2018年11月26日
*
*/
public class ZipUtils {
private static final int BUFFER_SIZE = 2 * 1024;
/**
* 压缩成ZIP 方法1
*
* @param srcDir 压缩文件夹路径
* @param out 压缩文件输出流
* @param keepTopDir 是否保留顶层文件夹
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(String srcDir, OutputStream out, boolean keepTopDir, boolean KeepDirStructure) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile, zos, sourceFile.getName(), keepTopDir, KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("生成文件完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 压缩成ZIP 方法2
*
* @param srcFiles 需要压缩的文件列表
* @param out 压缩文件输出流
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("生成文件完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 递归压缩方法
*
* @param sourceFile 源文件
* @param zos zip输出流
* @param name 压缩后的名称
* @param keepTopDir 是否保留顶层文件夹
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean keepTopDir, boolean keepDirStructure)
throws Exception {
byte[] buf = new byte[BUFFER_SIZE];
if (sourceFile.isFile()) {
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if (keepDirStructure) {
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();
}
} else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (keepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
if(keepTopDir) {
compress(file, zos, name + "/" + file.getName(), true, keepDirStructure);
} else {
compress(file, zos, file.getName(), true, keepDirStructure);
}
} else {
compress(file, zos, file.getName(), true, keepDirStructure);
}
}
}
}
}
/**
*
* zip解压
*
* @param srcFile zip源文件
* @param destDirPath 解压后的目标文件夹
* @throws RuntimeException 解压失败会抛出运行时异常
*
*/
public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
long start = System.currentTimeMillis();
// 判断源文件是否存在
if (!srcFile.exists()) {
throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
}
// 开始解压
ZipFile zipFile = null;
try {
zipFile = new ZipFile(srcFile);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
System.out.println("解析" + entry.getName());
// 如果是文件夹,就创建个文件夹
if (entry.isDirectory()) {
String dirPath = destDirPath + "/" + entry.getName();
File dir = new File(dirPath);
dir.mkdirs();
} else {
// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
File targetFile = new File(destDirPath + "/" + entry.getName());
// 保证这个文件的父文件夹必须要存在
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 将压缩文件内容写入到这个文件中
InputStream is = zipFile.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[BUFFER_SIZE];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 关流顺序,先打开的后关闭
fos.close();
is.close();
}
}
long end = System.currentTimeMillis();
System.out.println("解析文件完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("unzip error from ZipUtils", e);
} finally {
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/* public static void main(String[] args) throws Exception {
*//** 测试压缩方法1 *//*
FileOutputStream fos1 = new FileOutputStream(new File("c:/mytest01.zip"));
ZipUtils.toZip("D:/log", fos1, true, true);
*//** 测试压缩方法2 *//*
List<File> fileList = new ArrayList<>();
fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/jar.exe"));
fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/java.exe"));
FileOutputStream fos2 = new FileOutputStream(new File("c:/mytest02.zip"));
ZipUtils.toZip(fileList, fos2);
}*/
}Http工具类
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
/**
* <p>Http工具类
*
* <p>Http工具类,为系统提供通用Http访问操作方法:
*
* <p>1、发送GET请求;
* <p>2、发送POST请求。
*
*/
public class HttpUtil {
public static int httpStatus;
/**
* <p>发送GET请求
*
* @param url GET请求地址
*
* @return 与当前请求对应的响应内容字节数组
* @throws IOException
*
*/
public static byte[] doGet(String url) throws IOException {
return HttpUtil.doGet(url , null , null , 0);
}
/**
* <p>发送GET请求
*
* @param url GET请求地址
* @param headerMap GET请求头参数容器
*
* @return 与当前请求对应的响应内容字节数组
* @throws IOException
*
*/
public static byte[] doGet(String url , Map<?, ?> headerMap) throws IOException {
return HttpUtil.doGet(url , headerMap , null , 0);
}
/**
* <p>发送GET请求
*
* @param url GET请求地址
* @param proxyUrl 代理服务器地址
* @param proxyPort 代理服务器端口号
*
* @return 与当前请求对应的响应内容字节数组
* @throws IOException
*
*/
public static byte[] doGet(String url , String proxyUrl , int proxyPort) throws IOException {
return HttpUtil.doGet(url , null , proxyUrl , proxyPort);
}
/**
* <p>发送GET请求
*
* @param url GET请求地址
* @param headerMap GET请求头参数容器
* @param proxyUrl 代理服务器地址
* @param proxyPort 代理服务器端口号
*
* @return 与当前请求对应的响应内容字节数组
* @throws IOException
*
*/
@SuppressWarnings("deprecation")
public static byte[] doGet(String url , Map<?, ?> headerMap , String proxyUrl , int proxyPort) throws IOException {
byte[] content = null;
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);
if (headerMap != null) {
//头部请求信息
if (headerMap != null) {
Iterator<?> iterator = headerMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<?, ?> entry = (Entry<?, ?>) iterator.next();
getMethod.addRequestHeader(entry.getKey().toString() , entry.getValue().toString());
}
}
}
if (StringUtils.isNotBlank(proxyUrl)) {
httpClient.getHostConfiguration().setProxy(proxyUrl , proxyPort);
}
//设置成了默认的恢复策略,在发生异常时候将自动重试3次,在这里你也可以设置成自定义的恢复策略
httpClient.setConnectionTimeout(5000);
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT , 5000);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER , new DefaultHttpMethodRetryHandler() {});
InputStream inputStream = null;
try {
httpStatus = httpClient.executeMethod(getMethod);
if (httpStatus == HttpStatus.SC_OK) {
//读取内容
inputStream = getMethod.getResponseBodyAsStream();
content = IOUtils.toByteArray(inputStream);
} else {
content = getMethod.getStatusLine().toString().getBytes();
//System.err.println("Method failed: " + getMethod.getStatusLine());
}
} catch (IOException ex) {
throw ex;
} finally {
IOUtils.closeQuietly(inputStream);
getMethod.releaseConnection();
}
return content;
}
/**
* <p>发送POST请求
*
* @param url POST请求地址
* @param parameterMap POST请求参数容器
*
* @return 与当前请求对应的响应内容字节数组
* @throws IOException
*
*/
public static byte[] doPost(String url , Map<?, ?> parameterMap) throws IOException {
return HttpUtil.doPost(url , null , parameterMap , null , null , 0);
}
/**
* <p>发送POST请求
*
* @param url POST请求地址
* @param parameterMap POST请求参数容器
* @param paramCharset 参数字符集名称
*
* @return 与当前请求对应的响应内容字节数组
* @throws IOException
*
*/
public static byte[] doPost(String url , Map<?, ?> parameterMap , String paramCharset) throws IOException {
return HttpUtil.doPost(url , null , parameterMap , paramCharset , null , 0);
}
/**
* <p>发送POST请求
*
* @param url POST请求地址
* @param headerMap POST请求头参数容器
* @param parameterMap POST请求参数容器
* @param paramCharset 参数字符集名称
*
* @return 与当前请求对应的响应内容字节数组
* @throws IOException
*
*/
public static byte[] doPost(String url , Map<?, ?> headerMap , Map<?, ?> parameterMap , String paramCharset) throws IOException {
return HttpUtil.doPost(url , headerMap , parameterMap , paramCharset , null , 0);
}
/**
* <p>发送POST请求
*
* @param url POST请求地址
* @param parameterMap POST请求参数容器
* @param paramCharset 参数字符集名称
* @param proxyUrl 代理服务器地址
* @param proxyPort 代理服务器端口号
*
* @return 与当前请求对应的响应内容字节数组
* @throws IOException
*
*/
public static byte[] doPost(String url , Map<?, ?> parameterMap , String paramCharset , String proxyUrl , int proxyPort) throws IOException {
return HttpUtil.doPost(url , null , parameterMap , paramCharset , proxyUrl , proxyPort);
}
/**
* <p>发送POST请求
*
* @param url POST请求地址
* @param headerMap POST请求头参数容器
* @param parameterMap POST请求参数容器
* @param paramCharset 参数字符集名称
* @param proxyUrl 代理服务器地址
* @param proxyPort 代理服务器端口号
*
* @return 与当前请求对应的响应内容字节数组
* @throws IOException
*
*/
@SuppressWarnings("deprecation")
public static byte[] doPost(String url , Map<?, ?> headerMap , Map<?, ?> parameterMap , String paramCharset , String proxyUrl , int proxyPort) throws IOException {
byte[] content = null;
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
if (StringUtils.isNotBlank(paramCharset)) {
postMethod.getParams().setContentCharset(paramCharset);
postMethod.getParams().setHttpElementCharset(paramCharset);
}
if (headerMap != null) {
//头部请求信息
if (headerMap != null) {
Iterator<?> iterator = headerMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<?, ?> entry = (Entry<?, ?>) iterator.next();
postMethod.addRequestHeader(entry.getKey().toString() , entry.getValue().toString());
}
}
}
Iterator<?> iterator = parameterMap.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
postMethod.addParameter(key , (String) parameterMap.get(key));
}
if (StringUtils.isNotBlank(proxyUrl)) {
httpClient.getHostConfiguration().setProxy(proxyUrl , proxyPort);
}
//设置成了默认的恢复策略,在发生异常时候将自动重试3次,在这里你也可以设置成自定义的恢复策略
httpClient.setConnectionTimeout(5000);
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT , 5000);
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER , new DefaultHttpMethodRetryHandler() {});
InputStream inputStream = null;
try {
httpStatus = httpClient.executeMethod(postMethod);
if (httpStatus == HttpStatus.SC_OK) {
//读取内容
inputStream = postMethod.getResponseBodyAsStream();
content = IOUtils.toByteArray(inputStream);
} else {
content = postMethod.getStatusLine().toString().getBytes();
//System.err.println("Method failed: " + postMethod.getStatusLine());
}
} catch (IOException ex) {
throw ex;
} finally {
IOUtils.closeQuietly(inputStream);
postMethod.releaseConnection();
}
return content;
}
}- 本文固定链接: https://www.coordsoft.com/post/20.html
- 转载请注明: admin 于 生活随想 - zwgu 's world 发表
《本文》有 0 条评论