//得到这一条新闻的url
String url = item.getUrl();
//得到该网页的html
String html = getHtml(url, APPConst.UTF8).replaceAll("\r", "").replaceAll("\n", "").replaceAll("[\\s]{2,}", "");
//定义结果
String result = "";
Matcher matcher = APPConst.contentPattern.matcher(html);
if(matcher.find()) {
result = matcher.group(0);
//用来查找所有超链接的matcher
Matcher linkMatcher = APPConst.linkInHtml.matcher(result);
//用来查找所有图片的matcher
Matcher imgMatcher = APPConst.imgInHtml.matcher(result);
//超链接的List , 用于保存后替换
List<String> linkList = new ArrayList<String>();
//图片的List , 用于保存后替换
List<String> imgList = new ArrayList<String>();
//找到后添加到linkList中
while(linkMatcher.find()) {
//得到链接
String link = linkMatcher.group(1);
//得到正确的链接
link = getRightUrlBaseOnUrl(link, item.getUrl());
//将正确的链接添加到List中
linkList.add(link);
}
while(imgMatcher.find()) {
//得到图片地址
String img = imgMatcher.group(1);
//得到正确的图片
img = getRightUrlBaseOnUrl(img, item.getUrl());
//将正确的链接添加到list中
imgList.add(img);
}
//替换掉所有的超链接
for (String link : linkList) {
result = result.replaceFirst("href=\"(.+?)\"", "href='" + link + "'");
}
//替换掉所有的图片
for (String img : imgList) {
result = result.replaceFirst("src=\"(.+?)\"", "src='" + img + "'");
}
} else {
result = "<html><body>详情请看 : <a href='" + item.getUrl() + "'>" + item.getName() + "</a></body></html>";
}
return result;
public String getRightUrlBaseOnUrl(String nowUrl , String baseUrl) {
//定义结果
String result = "";
//如果是http开头就是结果
if(nowUrl.startsWith("http")) {
result = nowUrl ;
} else {
//如果是以../开头 , 需要统计../的个数
if(nowUrl.startsWith("../")) {
//定义../的正则
Pattern p = new Pattern("\\.\\./");
//使用正则匹配原url
Matcher matcher = p.matcher(nowUrl);
//定义个数
int count = 0 ;
while(matcher.find()) {
//如果发现则计数加1
count ++;
}
//对referer进行初始化 加入baseUrl为http://www.sina.com.cn/joy/hello/nihao.html , 则初始化为http://www.sina.com.cn/joy/hello
String baseUrlBack = baseUrl.substring(0, baseUrl.lastIndexOf("/"));
//然后向前查找count个斜杠
for (int i = 1; i <= count; i++) {
baseUrlBack = baseUrlBack.substring(0, baseUrlBack.lastIndexOf("/"));
}
//将nowUrl中的../替换掉
while(nowUrl.startsWith("../")) {
nowUrl = nowUrl.replace("../", "");
}
//将两个结果合并起来
result = baseUrlBack + "/" + nowUrl;
} else {
//不以http开头 , 也不以../开头
//对referer进行初始化 加入baseUrl为http://www.sina.com.cn/joy/hello/nihao.html , 则初始化为http://www.sina.com.cn/joy/hello
String baseUrlBack = baseUrl.substring(0, baseUrl.lastIndexOf("/"));
//将两个结果合并起来
result = baseUrlBack + "/" + nowUrl;
}
}
return result;
}
import jregex.Pattern;
//程序中的一些常量
public class APPConst {
/**
* 声明编码gb2312
*/
public static final String GB2312 = "gb2312";
/**
* 声明编码utf-8
*/
public static final String UTF8 = "UTF-8";
/**
* 获得新闻内容的正则表达式
*/
public static Pattern contentPattern = new Pattern("<table width=\"95%\".+?相关链接");
/**
* 内容中的超链接替换的正则表达式
*/
public static Pattern linkInHtml = new Pattern("href=\"(.+?)\"");
/**
* 内容中的图片替换的正则表达式
*/
public static Pattern imgInHtml = new Pattern("src=\"(.+?)\"");
}