private static final Logger logger = Logger.getLogger(ImageUtil.class);
// 图片压缩宽度
private static final Integer ratio = 480;
public static List<String> getImgUrl(String content) {
String imgEx_script = "<img.*src\\s*=\\s*(.*?)[^>]*?>"; // 定义img的正则表达式
Pattern p_script = Pattern.compile(imgEx_script, Pattern.CASE_INSENSITIVE);
Matcher m_script = p_script.matcher(content);
List<String> list = new ArrayList<String>();
while (m_script.find()) {
Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(m_script.group());
while (m.find()) {
list.add(m.group(1));
}
}
/*
* if (m_script.find()) { Matcher m =
* Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)"
* ).matcher(m_script.group(0)); if (m.find()) { list.add(m.group(1)); }
* }
*/
return list;
}
private static String downloadFromUrl(String url, String dir) {
String fileName = null;
try {
// -------------------------------------
// System.setProperty("http.proxySet", "true");
// System.setProperty("http.proxyHost", "xxx.com.cn");
// System.setProperty("http.proxyPort", "80");
// ---------------------------------------
URL httpurl = new URL(url);
fileName = getFileNameFromUrl(url);
File file = new File(dir + File.separator + fileName);
File fileDir = new File(dir);
FileUtils.forceMkdir(fileDir);
FileUtils.copyURLToFile(httpurl, file);
} catch (Exception e) {
logger.error("downloadFromUrl", e);
}
return fileName;
}
private static String getFileNameFromUrl(String url) {
String name = new Long(System.currentTimeMillis()).toString() + ".X";
int index = url.lastIndexOf("/");
if (index > 0) {
name = url.substring(index + 1);
if (name.trim().length() > 0) {
return name.replace("=", ".");
}
}
return name;
}
public static File getUrlFile(String url, String dir) {
File file = null;
if (url.startsWith("http://")) {
String fileName = downloadFromUrl(url, dir);
file = new File(dir + File.separator + fileName);
} else {
file = new File(url);
}
return file;
}
private static File getReduceFile(File imgFile) throws IOException {
String filename = imgFile.getName();
String name = filename.substring(0, filename.lastIndexOf("."));
String extensionName = StringUtils.substring(filename, StringUtils.lastIndexOf(filename, "."));
File reduceFile = new File(imgFile.getParent(), name + "_" + extensionName);
FileUtils.copyFile(imgFile, reduceFile);
return reduceFile;
}
/**
* 图片自动压缩
*
* @param imgFile
* @return
*/
public static Icon imageReduce(File imgFile) {
// 在缓存中构造Image对象
Icon ret = null;
double high = 0.0;
double scale = 0.0;
try {
File reduceFile = getReduceFile(imgFile);
// 把图像数据获取到存在BufferedImage里边
BufferedImage bi = ImageIO.read(reduceFile);
if (!reduceFile.exists()) {
reduceFile.mkdirs();
}
// 宽度超过比例压缩
if (bi.getWidth() > ratio) {
// 想要的宽度/图片的宽度,得出比例
scale = ratio.doubleValue() / bi.getWidth();
// 比例*高度为等比的高度
high = bi.getHeight() * scale;
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(scale, scale), null);
Image item = bi.getScaledInstance((int) ratio, (int) high, BufferedImage.SCALE_DEFAULT);
item = op.filter(bi, null);
ImageIO.write((BufferedImage) item, "gif", reduceFile);
ret = new ImageIcon(reduceFile.getPath());
} else {
ret = new ImageIcon(reduceFile.getPath());
}
} catch (Exception e1) {
logger.error("图片压缩异常", e1);
}
return ret;
}
public static String imageReduceUrl(String uploadDir, String url) {
String result = null;
// 在缓存中构造Image对象
Icon ret = null;
double high = 0.0;
double scale = 0.0;
try {
// ----本地环境需要设置代理----
// System.setProperty("proxySet", "true");
// System.setProperty("proxyHost", "xxx.com.cn");
// System.setProperty("proxyPort", "80");
// ----------------------
URL sUrl = new URL(url);
String fileName = getFileNameFromUrl(url);
File imgFile = new File(uploadDir, fileName);
if (!imgFile.exists()) {
FileUtils.copyURLToFile(sUrl, imgFile);
}
File reduceFile = getReduceFile(imgFile);
// 把图像数据获取到存在BufferedImage里边
BufferedImage bi = ImageIO.read(sUrl);
// 宽度超过比例压缩
if (bi.getWidth() > ratio) {
// 想要的宽度/图片的宽度,得出比例
scale = ratio.doubleValue() / bi.getWidth();
// 比例*高度为等比的高度
high = bi.getHeight() * scale;
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(scale, scale), null);
Image item = bi.getScaledInstance((int) ratio, (int) high, BufferedImage.SCALE_DEFAULT);
item = op.filter(bi, null);
ImageIO.write((BufferedImage) item, "gif", reduceFile);
ret = new ImageIcon(reduceFile.getPath());
} else {
ret = new ImageIcon(reduceFile.getPath());
}
result = reduceFile.getName();
} catch (Exception e1) {
logger.error("图片压缩异常", e1);
}
return result;
}
/**
* 获取图片宽度
*
* @return
*/
public static int getImageWidth(String url, File file) {
int result = 0;
try {
BufferedImage img = ImageIO.read(file);
result = img.getWidth();
} catch (Exception e) {
logger.error("获取图片宽度异常", e);
}
return result;
}
/**
* 正文添加封面图片
*
* @param imgUrl
* @param content
* @return
*/
public static String addCoverImg(String imgUrl, String content) {
if (StringUtils.isNotEmpty(content) && content.startsWith("<img")) {
Document doc = Jsoup.parse(content);
Elements pngs = doc.select("img");
if (pngs != null && !pngs.isEmpty()) {
if (imgUrl.equals(pngs.first().attr("src"))) {
content = content.replaceFirst(pngs.first().toString(), "");
content = content.replaceFirst("<br />", "");
content = content.replaceFirst("<br />", "");
}
}
}
return "<img src=\"" + imgUrl + "\" /><br />" + content;
}
/**
* 正文移除封面图片
*
* @param imgUrl
* @param content
* @return
*/
public static String removeCoverImg(String imgUrl, String content) {
if (StringUtils.isNotEmpty(content) && content.startsWith("<img")) {
Document doc = Jsoup.parse(content);
Elements pngs = doc.select("img");
if (pngs != null && !pngs.isEmpty()) {
if (imgUrl.equals(pngs.first().attr("src"))) {
content = content.replaceFirst(pngs.first().toString(), "");
content = content.replaceFirst("<br />", "");
content = content.replaceFirst("<br />", "");
}
}
}
return content;
}
public static void main(String[] args) throws Exception {
// downloadFromUrl("http://xxx/0wx_fmt=jpeg",
// "d:/");
// imageReduceUrl("d:/pic/",
// "http://xxx:8080/resources/images/banner1.jpg");
File file = new File(
"D:/Koala.jpg");
// getReduceFile(file);
imageReduce(file);
}
}
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SendURLUtil {
private static URL sUrl = null;
private static HttpURLConnection httpURlConnection = null;
private static final Logger logger = LoggerFactory.getLogger(SendURLUtil.class);
/*
* 发送url地址并获取响应消息
*/
public static String sendURL(String url, String encode) {
BufferedReader reader = null;
String result = null;
// ByteArrayOutputStream baos = null;
try {
// 发送请求
sUrl = new URL(url);
// SocketAddress addr = new InetSocketAddress("xxx.com.cn",
// 80);
// Proxy typeProxy = new Proxy(Proxy.Type.HTTP, addr);
// httpURlConnection = (HttpURLConnection)
// sUrl.openConnection(typeProxy);
httpURlConnection = (HttpURLConnection) sUrl.openConnection();
httpURlConnection.setRequestMethod("POST");
httpURlConnection.setDoOutput(true);
httpURlConnection.setDoInput(true);
// 设置连接主机超时
httpURlConnection.setConnectTimeout(15000);
// 设置从主机读取数据超时
httpURlConnection.setReadTimeout(120000);
httpURlConnection.setUseCaches(false);
// 设定传送的内容类型是可序列化的java对象
httpURlConnection.setRequestProperty("Content-type", "text/xml");
httpURlConnection.connect();
// 读取返回内容
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(httpURlConnection.getInputStream(), encode));
String temp;
while ((temp = reader.readLine()) != null) {
buffer.append(temp);
}
result = buffer.toString();
// int i = -1;
// baos = new ByteArrayOutputStream();
// while ((i = reader.read()) != -1) {
// baos.write(i);
// }
// result = baos.toString();
} catch (Exception e) {
logger.error("请求异常:", e);
return null;
} finally {
try {
if (httpURlConnection != null) {
httpURlConnection.disconnect();
}
} catch (Exception e) {
logger.error("錯誤:", e);
}
// 关闭输入输出流
IOUtils.closeQuietly(reader);
// IOUtils.closeQuietly(baos);
}
return result;
}
/*
* 发送post请求获取响应消息
*/
public static String sendPostReq(String url, String content) throws Exception {
String result = null;
DataOutputStream outStrm = null;
BufferedReader reader = null;
ByteArrayOutputStream baos = null;
try {
// 发送请求
sUrl = new URL(url);
// 本地环境需要设置代理
// Properties systemProperties = System.getProperties();
// systemProperties.setProperty("http.proxyHost",
// "xxx.com.cn");
// systemProperties.setProperty("http.proxyPort", "80");
// 本地环境需要设置代理
// SocketAddress addr = new InetSocketAddress("xxx.com.cn",
// 80);
// Proxy typeProxy = new Proxy(Proxy.Type.HTTP, addr);
// httpURlConnection = (HttpURLConnection)
// sUrl.openConnection(typeProxy);
httpURlConnection = (HttpURLConnection) sUrl.openConnection();
// 设置请求方式,缺省为get方式
httpURlConnection.setRequestMethod("POST");
// 设置是否向httpUrlConnection输出,post请求需要设为true,默认情况下是false;
httpURlConnection.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
httpURlConnection.setDoInput(true);
// 设置连接主机超时
httpURlConnection.setConnectTimeout(15000);
// 设置从主机读取数据超时
httpURlConnection.setReadTimeout(120000);
// Post 请求不能使用缓存
httpURlConnection.setUseCaches(false);
// 设定传送的内容类型是可序列化的java对象
httpURlConnection.setRequestProperty("Content-type", "text/xml");
// 连接,配置必须要在connect之前完成,
httpURlConnection.connect();
// 此处getOutputStream会隐含的进行connect,所以在开发中不调用上述的connect()也可以。
outStrm = new DataOutputStream(httpURlConnection.getOutputStream());
// 向对象输出流写出数据,这些数据将存到内存缓冲区中
outStrm.write(content.toString().getBytes("UTF-8"));
// 刷新对象输出流,将任何字节都写入潜在的流中(此处为ObjectOutputStream)
outStrm.flush();
// 关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中,
// 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器
outStrm.close();
// 读取返回内容
// inStrm = httpURlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(httpURlConnection.getInputStream(), "utf-8"));
// <===注意,实际发送请求的代码段就在这里
// reader = new BufferedReader(new
// InputStreamReader(httpURlConnection.getInputStream()));
int i = -1;
baos = new ByteArrayOutputStream();
while ((i = reader.read()) != -1) {
baos.write(i);
}
result = baos.toString();
} catch (Exception e) {
logger.error("请求异常:" + e.getMessage(), e);
throw e;
} finally {
try {
if (httpURlConnection != null) {
httpURlConnection.disconnect();
}
} catch (Exception e) {
logger.error("錯誤:", e);
}
// 关闭输入输出流
IOUtils.closeQuietly(outStrm);
IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(baos);
}
return result;
}
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpServiceUtils {
private static final Logger log = LoggerFactory.getLogger(HttpServiceUtils.class);
private static volatile CloseableHttpClient httpClient;
private static final String DEFAULT_ENCODING = "UTF-8";
public static CloseableHttpClient getHttpClient() {
if (httpClient == null) {
synchronized (HttpServiceUtils.class) {
if (httpClient == null) {
httpClient = HttpClientBuilder.create().build();
}
}
}
return httpClient;
}
/**
* post请求
*
* @param url
* @param content
* @return
*/
public static String postRequest(String url, String content) {
return postRequest(url, content, DEFAULT_ENCODING, DEFAULT_ENCODING);
}
/**
* post请求
*
* @param url
* @param content
* @param requestEncode
* @param responseEncode
* @return
*/
public static String postRequest(String url, String content, String requestEncode, String responseEncode) {
log.debug("Post request [" + url + "] with content [" + content + "]");
String result = null;
CloseableHttpResponse response = null;
try {
HttpPost post = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000)
.setConnectionRequestTimeout(30000).build();
post.setConfig(requestConfig);
post.setEntity(new StringEntity(content, ContentType.create("text/xml", requestEncode)));
CloseableHttpClient client = getHttpClient();
response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, responseEncode);
EntityUtils.consume(entity);
log.debug("request successful with content [" + content + "], response [" + result + "]");
} else {
log.debug("request failed with content [" + content + "], status code [" + statusCode + "]");
}
} catch (Exception e) {
log.debug("post request failed with content [" + content + "]!", e);
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
// ignore
}
}
return result;
}
/**
* post请求
*
* @param paramMap
* @param url
* @return
*/
public static String postRequest(String url, Map<String, Object> paramMap) {
return postRequest(url, paramMap, "UTF-8", "UTF-8");
}
/**
* post请求
*
* @param url
* @param paramMap
* @param requestEncode
* @param responseEncode
* @return
*/
public static String postRequest(String url, Map<String, Object> paramMap, String requestEncode,
String responseEncode) {
log.debug("Post request [" + url + "] with paramMap [" + paramMap + "]");
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
for (Entry<String, Object> entry : paramMap.entrySet()) {
pairList.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
String result = null;
CloseableHttpResponse response = null;
try {
HttpPost post = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000)
.build();
post.setConfig(requestConfig);
post.setEntity(new UrlEncodedFormEntity(pairList, requestEncode));
CloseableHttpClient client = getHttpClient();
response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, responseEncode);
EntityUtils.consume(entity);
log.debug("request successful with paramMap [" + paramMap + "], response [" + result + "]");
} else {
log.debug("request failed with paramMap [" + paramMap + "], status code [" + statusCode + "]");
}
} catch (Exception e) {
log.debug("post request failed with paramMap [" + paramMap + "]!", e);
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
// ignore
}
}
return result;
}
public static void main(String[] args) {
}
}