crawler_基础之_java.net.HttpURLConnection 访问网络资源
java访问网络资源 由底层到封装 为 scoket==> java.net.HttpURLConnection==>HttpClient
这次阐述先 java.net.HttpURLConnection 的方式 ,好处是用导包 ,jdk原生自带的。
HtmlUtil 包含尝试重连(3次) ,编码识别,保存文件到磁盘
package com.cph.crawler.core.utils; import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; /**
* 类说明:html有关的操作 <br>
* --22下午08::20创建<br>
*
* @author cphmvp
*/
public final class HtmlUtil {
public final static Log LOG = LogFactory.getLog(HtmlUtil.class);
static String defaultEncoding = "utf-8";
static HttpURLConnection httpURLConnection = null;
static URL urlModel = null;
// 链接超时时间
static int connectTimeout = ;
// 读取响应超时时间
static int readTimeout = ; /**
* 下载图片<br>
*
* @param url
* 图片的下载地址<br>
* @param savePath
* 保存路径<br>
* @throws IOException
*/
@SuppressWarnings("resource")
public static void downloadAndSavePictureToDisk(String url, String savePath)
throws IOException {
urlModel = new URL(url);
httpURLConnection = (HttpURLConnection) urlModel.openConnection();
httpURLConnection.setConnectTimeout(connectTimeout);
httpURLConnection.setReadTimeout(readTimeout);
httpURLConnection.setDoOutput(true);
InputStream is = httpURLConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
FileOutputStream fw = null;
File f = new File(savePath.substring(, savePath.lastIndexOf("/"))); if (!f.exists()) {
f.mkdirs();
}
File eixtsFile = new File(savePath);
if (eixtsFile.exists()) {
return;
}
fw = new FileOutputStream(savePath, true);
int num = -;
while ((num = is.read()) != (-))// 是否读完所有数据
{
fw.write(num);// 将数据写往文件
}
rd.close();
is.close();
if (httpURLConnection != null) {
httpURLConnection.disconnect();
} } /**
* 讲url后面的参数进行编码
*
* @param url
* @return
* @throws UnsupportedEncodingException
*/
private static String encodParamters(String url)
throws UnsupportedEncodingException {
String returnStr = new String(url);
String regex = "=([^&]+)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(url);
while (m.find()) {
String replaceStr = m.group();
returnStr = returnStr.replaceFirst(replaceStr,
URLEncoder.encode(replaceStr, "utf-8"));
}
return returnStr;
} /**
* 获取会话的JSESSIONID
*
* @param url
* @return
*/
public static String getSession(String url) {
String sessionId = "";
try {
urlModel = new URL(url);
httpURLConnection = (HttpURLConnection) urlModel.openConnection();
httpURLConnection.setConnectTimeout(connectTimeout);
httpURLConnection.setReadTimeout(readTimeout);
String cookieVal = null;
String key = null;
for (int i = ; (key = httpURLConnection.getHeaderFieldKey(i)) != null; i++) {
if (key.equalsIgnoreCase("set-cookie")) {
cookieVal = httpURLConnection.getHeaderField(i);
cookieVal = cookieVal.substring(, cookieVal.indexOf(";"));
sessionId = sessionId + cookieVal + ";";
}
} } catch (MalformedURLException e) {
LOG.error(e);
} catch (IOException e) {
LOG.error(e);
}
return sessionId;
} /**
* 下载页面</br>
*
* @param page
* </br>
* @return 页面源码
* @throws IOException
* @throws UnsupportedEncodingException
*/
public static StringBuffer downloadHtml(String url,String encoding) {
StringBuffer sb = new StringBuffer();
BufferedReader in = null;
int tryNum = ;
while (true) {
try {
if (tryNum > ) {
String ecodingUrl = encodParamters(url);
urlModel = new URL(ecodingUrl);
} else {
urlModel = new URL(url);
}
httpURLConnection = (HttpURLConnection) urlModel
.openConnection();
httpURLConnection.setConnectTimeout(connectTimeout);
httpURLConnection.setReadTimeout(readTimeout);
httpURLConnection
.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)");
String redirectUrl = httpURLConnection.getURL().toString();
if (!redirectUrl.equals(url)) {
LOG.info(url + "重定向后为" + redirectUrl);
}
String charSetHeader = httpURLConnection
.getHeaderField("Content-Type");
String charSet = null;
if (charSetHeader != null) {
Pattern p = Pattern.compile("charset=[\"']?(.*?)['\"]");
Matcher m = p.matcher(charSetHeader);
if (m.find())
charSet = m.group().trim();
if (null == charSet) {
charSet = encoding;
}
} charSet = (charSet == null ? encoding : charSet);
in = new BufferedReader(new InputStreamReader(
httpURLConnection.getInputStream(), charSet));
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine + "\n");
inputLine = null;
}
if (in != null)
try {
in.close();
} catch (IOException e) {
LOG.error(e);
}
if (httpURLConnection != null)
httpURLConnection.disconnect();
break;
} catch (Exception e) {
if (tryNum++ == ) {
LOG.error("download page error [ " + urlModel + " ] ");
return null;
}
LOG.warn(tryNum + "次下载失败", e);
}
}
return sb; }
/**
* 下载页面</br>
*
* @param page
* </br>
* @return 页面源码
* @throws IOException
* @throws UnsupportedEncodingException
*/
public static StringBuffer downloadHtml(String url) {
StringBuffer sb = new StringBuffer();
BufferedReader in = null;
int tryNum = ;
while (true) {
try {
if (tryNum > ) {
String ecodingUrl = encodParamters(url);
urlModel = new URL(ecodingUrl);
} else {
urlModel = new URL(url);
}
httpURLConnection = (HttpURLConnection) urlModel
.openConnection();
httpURLConnection.setConnectTimeout(connectTimeout);
httpURLConnection.setReadTimeout(readTimeout);
httpURLConnection
.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)");
String redirectUrl = httpURLConnection.getURL().toString();
if (!redirectUrl.equals(url)) {
LOG.info(url + "重定向后为" + redirectUrl);
}
String charSetHeader = httpURLConnection
.getHeaderField("Content-Type");
String charSet = null;
if (charSetHeader != null) {
Pattern p = Pattern.compile("charset=[\"']?(.*?)['\"]");
Matcher m = p.matcher(charSetHeader);
if (m.find())
charSet = m.group().trim();
if (null == charSet) {
charSet = defaultEncoding;
}
} charSet = (charSet == null ? defaultEncoding : charSet);
in = new BufferedReader(new InputStreamReader(
httpURLConnection.getInputStream(), charSet));
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine + "\n");
inputLine = null;
}
if (in != null)
try {
in.close();
} catch (IOException e) {
LOG.error(e);
}
if (httpURLConnection != null)
httpURLConnection.disconnect();
break;
} catch (Exception e) {
if (tryNum++ == ) {
LOG.error("download page error [ " + urlModel + " ] ");
return null;
}
LOG.warn(tryNum + "次下载失败", e);
}
}
return sb; } }
crawler_基础之_java.net.HttpURLConnection 访问网络资源的更多相关文章
- 使用VC建立网络连接并访问网络资源
目录 1. 提出问题 2. 解决方案 1. 提出问题 在windows下可以通过系统操作,将局域网的资源映射到本地,从而实现像本地数据一样访问网络资源.实际上这些步骤也可通过代码调用win32函数实现 ...
- java成神之——HttpURLConnection访问api
HttpURLConnection 访问get资源 访问post资源 访问Delete资源 获取状态码 结语 HttpURLConnection 访问get资源 HttpURLConnection c ...
- 【CUDA 基础】4.3 内存访问模式
title: [CUDA 基础]4.3 内存访问模式 categories: - CUDA - Freshman tags: - 内存访问模式 - 对齐 - 合并 - 缓存 - 结构体数组 - 数组结 ...
- crawler_基础之_httpclient 访问网络资源
先粘贴一个 简单版的,后期再修改 pom文件 <dependency> <groupId>org.apache.httpcomponents</groupId> & ...
- 简单使用URLConnection、HttpURLConnection和HttpClient访问网络资源
URL的openConnection方法将返回一个URLConnection,该对象表示应用程序和URL之间的通信连接.程序可以通过它的实例向该URL发送请求,读取URL引用的资源. 下面通过一个简单 ...
- Java多线程基础——对象及变量并发访问
在开发多线程程序时,如果每个多线程处理的事情都不一样,每个线程都互不相关,这样开发的过程就非常轻松.但是很多时候,多线程程序是需要同时访问同一个对象,或者变量的.这样,一个对象同时被多个线程访问,会出 ...
- 关于安卓开发当中通过java自带的HttpURLConnection访问XML的java.io.EOFException问题
刚接触安卓开发,试着写个小程序熟悉下,就写了天气预报的小程序,通过httpUrlConnection读流的方式来获取网络公共接口提供的天气XML信息.但在建立http连接时一直报java.io.EOF ...
- 通过HTTP访问网络资源
添加访问网络的权限:<uses-permission android:name="android.permission.INTERNET"/> package com. ...
- Android网络:HTTP之利用HttpURLConnection访问网页、获取网络图片实例 (附源码)
http://blog.csdn.net/yanzi1225627/article/details/22222735 如前文所示的TCP局域网传送东西,除了对传输层的TCP/UDP支持良好外,Andr ...
随机推荐
- 乐在其中设计模式(C#) - 策略模式(Strategy Pattern)
原文:乐在其中设计模式(C#) - 策略模式(Strategy Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 策略模式(Strategy Pattern) 作者:webabc ...
- 理解JavaScript的闭包
在JS这块,免不了被问什么是闭包. 从一个常见的循环问题说起. 有一个ul列表, 里面有5个li标签,我希望点击每个li标签的时候,弹出每个li标签对应的索引值(第一个弹出0,第二个弹出1...). ...
- Directx11 xnamath.h 报错
xnamath.h 报错: 在标识符“XMConvertToRadians”的前面 如下报错 >d:\program files\microsoft directx sdk (june )\in ...
- 构建安全的Xml Web Service系列之wse之证书存储位置
原文:构建安全的Xml Web Service系列之wse之证书存储位置 我们在前几天对xml web service的安全性提出了一些建议,大家可以通过以下地址访问: 构建安全的Xml Web Se ...
- 如何解决vector 析构函数的异常 opencv Assert _CrtIsValidHeapPointer
一气呵成代码,但是,当发生执行_CrtIsValidHeapPointer例外,去搭调了一上午Bug.最终获得 跟踪定位到 _CrtIsValidHeapPointer ,注意到 g 8h&quo ...
- Nagios显示器mysql定从库: libmysqlclient.so.18: cannot open shared object file: No such
做mysql的slave时间监控,必须check_mysql文字,check当误差: error while loading shared libraries: libmysqlclient.so.1 ...
- Android - 和其他APP交互 - 让其他app启动你的activity
前面的两篇文章主要讲了一个方面:从app中启动其他app.但是如果你的app可以处理对其他app有用的操作,你的app也应该响应其他app的操作请求.例如,如果你创建了一个社交app可以分享信息和图片 ...
- 查看oracle数据库的连接数以及用户
查看oracle数据库的连接数以及用户 11.查询oracle的连接数2select count(*) from v$session;32.查询oracle的并发连接数4select count(*) ...
- 【Android基础】listview控件的使用(4)-----自定义布局的listview的使用
前面我介绍了listview控件的不同用法,但是这些用法在实际的开发项目中是不足以满足需求的,因为前面的几种用法只能简单的显示文本信息,而且布局都比较单一,很难做出复杂的结果,在实际的开发项目中,90 ...
- VisualStudioOnline协同工作流程
VisualStudioOnline协同工作流程 项目负责人登陆自己的vsonline新建项目就不多说了. 直接从邀请队友开始 项目负责人操作 被邀请的邮箱必须是微软的邮箱(也就是可以登录visual ...