package com.fh.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GetWeb {
public static String getHtmlCode(String httpUrl) throws IOException {
String content = "";
URL url = new URL(httpUrl);
BufferedReader reader = new BufferedReader(new InputStreamReader(
url.openStream(), "utf-8"));
String input;
while ((input = reader.readLine()) != null) {
content += input;
}
reader.close();
return content;
}
public static List<String> getImagePathList(String httpUrl)
throws IOException {
String searchImgReg = "<(img|IMG)\\b[^>]*\\b(src|SRC|src2|SRC2)\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic)\\b)[^>]*>";
List<String> imgList = new ArrayList<String>();
String content = null;
content = getHtmlCode(httpUrl);
Pattern pattern = Pattern.compile(searchImgReg);
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
String quote = matcher.group(3);
String imgsrc = (quote == null || quote.trim().length() == 0) ? matcher.group(4).split("\\s+")[0] : matcher.group(4);
if (!imgsrc.startsWith("http://") && !imgsrc.startsWith("https://")) {
String[] httpUrlarr = httpUrl.split("/");
String wwwhost = httpUrlarr[0] + "//" + httpUrlarr[2];
if(!isNetFileAvailable(wwwhost + "/" + imgsrc)){
for(int i=3;i<httpUrlarr.length;i++){
wwwhost = wwwhost + "/" + httpUrlarr[i];
if(isNetFileAvailable(wwwhost + "/" + imgsrc)){
imgsrc = wwwhost + "/" + imgsrc;
break;
}
}
}else{
imgsrc = wwwhost + "/" + imgsrc;
}
}
imgList.add(imgsrc);
}
return imgList;
}
public static String getTilte(String httpUrl) {
String searchTitle = "(<title>|<TITLE>)(.*?)(</title>|</TITLE>)";
Pattern pattern = Pattern.compile(searchTitle);
try {
Matcher matcher = pattern.matcher(getHtmlCode(httpUrl));
while (matcher.find()) {
return matcher.group(2);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static boolean isNetFileAvailable(String strUrl) {
InputStream netFileInputStream = null;
try {
URL url = new URL(strUrl);
URLConnection urlConn = url.openConnection();
netFileInputStream = urlConn.getInputStream();
if (null != netFileInputStream) {
return true;
} else {
return false;
}
} catch (IOException e) {
return false;
} finally {
try {
if (netFileInputStream != null)
netFileInputStream.close();
} catch (IOException e) {
}
}
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結