HttpClient4.3 使用经验(一) 简单使用
package com.wp.nevel.base.utils; import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.UnknownHostException;
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.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.junit.Test; import com.wp.nevel.base.exception.ParserException;
import com.wp.nevel.base.service.impl.LogServiceHelp; public class HttpClientUtils { public static Logger logger = Logger.getLogger( LogServiceHelp.class); private static HttpClient httpclient; static {
httpclient = HttpClients.createDefault();
} @Test
public void test(){
String url="http://www.shuchongw.com/files/article/html/23/23114/index.html";
doGetHtmlContent2byte(url);
} /**
* 根据简单url获取网页数据,转换成byte [] 存储
* */
public static byte[] doGetHtmlContent2byte(String url) {
CloseableHttpResponse response = null;
byte[] resultByte = {};
try {
HttpGet get = new HttpGet(url);
System.out.println(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
get.setConfig(requestConfig);
try {
response = (CloseableHttpResponse) HttpClientUtils.httpclient.execute(get);
} catch (UnknownHostException e) {
e.printStackTrace();
logger.info("链接主网失败");
}
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
resultByte = EntityUtils.toByteArray(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
} finally {
try {
if(response!=null){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultByte;
} /**
* 根据复杂url获取网页数据,转换成byte [] 存储
* @throws ParserException
* @throws IOException
* @throws UnknownHostException
* @throws ClientProtocolException
* @throws SocketException
* */
public static byte [] doGetHtmlByParams2Byte(Map<String, String> params, String paramsEncoding, String url) {
if (params != null) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (Entry<String, String> entry : params.entrySet()) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
if (!formparams.isEmpty()) {
String paramsStr = URLEncodedUtils.format(formparams, paramsEncoding!=null?paramsEncoding:"utf-8");
url = url + "?" + paramsStr;
}
}
return doGetHtmlContent2byte(url);
} /**
* 根据复杂url获取网页数据,转换成String 存储
* @throws ParserException
* @throws IOException
* @throws UnknownHostException
* @throws ClientProtocolException
* @throws SocketException
* */
public static String doGetHtmlByParams2Text(Map<String, String> params, String paramsEncoding, String url,String htmlEncoding) throws ClientProtocolException, UnknownHostException, SocketException{
try {
return getHtmlContentByText(doGetHtmlByParams2Byte(params,paramsEncoding,url),htmlEncoding!=null?htmlEncoding:"utf-8");
} catch (Exception e) {
e.printStackTrace();
return "";
}
} /**
* 根据简单url获取网页数据,转换成String 存储
* @throws ParserException
* @throws IOException
* @throws UnknownHostException
* @throws ClientProtocolException
* @throws SocketException
* */
public static String doGetHtmlContentToString(String url, String encoding){
try {
return getHtmlContentByText(doGetHtmlContent2byte(url),encoding);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 根据简单url获取网页图片数据, 保存路径[saveImagePath]
* @throws ParserException
* @throws IOException
* @throws UnknownHostException
* @throws ClientProtocolException
* @throws SocketException
* */
public static void getHtml2Image(String url,String saveImagPath){
try {
downloadData(doGetHtmlContent2byte(url),saveImagPath);
} catch (Exception e) {
e.printStackTrace();
}
} public static String getHtmlContentByText(byte [] htmlBytes, String encoding){
try {
return new String (htmlBytes,encoding!=null?encoding:"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
} /**
* 执行下载io
*
* @param byte [] data 网页字节流,filename 存储地址和文件名 return
* */
public static void downloadData(byte[] data, String filename) {
try {
DataOutputStream writer = new DataOutputStream(
new FileOutputStream(new File(filename)));
BufferedOutputStream out = new BufferedOutputStream(writer);
out.write(data);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} public static String readFile(String filename) throws IOException{
String xmlContent =null;
File file = new File(filename);
BufferedReader reader =null;
try {
if(!file.exists()){
new RuntimeException("文件不存在");
return xmlContent;
}
StringBuilder buider = new StringBuilder();
String readata ="";
reader = new BufferedReader(new FileReader(file));
while(true){
readata = reader.readLine();
if(readata==null){
break;
}
buider.append(readata).append("\n");
}
xmlContent=buider.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
if(reader!=null)
reader.close();
}
return xmlContent;
} public static byte [] doGetByteByHttpclient2Url(HttpContext httpContext,CloseableHttpClient client,String url){
byte [] resultBytes = null;
try {
HttpGet get = new HttpGet(url);
CloseableHttpResponse response =client.execute(get, httpContext);
int status = response.getStatusLine().getStatusCode();
System.out.println("链接状态="+status);
if(status!=200)
return resultBytes;
HttpEntity entity = response.getEntity();
resultBytes = EntityUtils.toByteArray(entity);
} catch (ClientProtocolException e) {
throw new RuntimeException("失败连接地址"+url, e);
} catch (IOException e) {
throw new RuntimeException("失败连接地址"+url, e);
}
if(resultBytes==null){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return resultBytes;
} }
HttpClient4.3 使用经验(一) 简单使用的更多相关文章
- HttpClient中post请求http、https示例
HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...
- Haproxy基础知识 -运维小结
开源软件负载均衡器 现在常用的三大开源软件负载均衡器分别是Nginx.LVS.Haproxy. 在之前的文章中已经对比了这三个负载均衡软件, 下面根据自己的理解和使用经验, 再简单说下这三个负载均衡软 ...
- HttpClient4.5简单使用
一.HttpClient简介 HttpClient是一个客户端的HTTP通信实现库,它不是一个浏览器.关于HTTP协议,可以搜索相关的资料.它设计的目的是发送与接收HTTP报文.它不会执行嵌入在页面中 ...
- dubbo学习过程、使用经验分享及实现原理简单介绍
一.前言 部门去年年中开始各种改造,第一步是模块服务化,这边初选dubbo试用在一些非重要模块上,慢慢引入到一些稍微重要的功能上,半年时间,学习过程及线上使用遇到的些问题在此总结下. 整理这篇文章差不 ...
- 【Dubbo基础】dubbo学习过程、使用经验分享及实现原理简单介绍
一.前言 部门去年年中开始各种改造,第一步是模块服务化,这边初选dubbo试用在一些非重要模块上,慢慢引入到一些稍微重要的功能上,半年时间,学习过程及线上使用遇到的些问题在此总结下. 整理这篇文章差不 ...
- jqGrid使用经验分享(一)——jqGrid简单使用、json格式和jsonReader介绍
广大的读者朋友们大家好,很高兴又可以在博客中和大家分享我的开发经验了. 此次,我准备向大家介绍一个非常好用的jQuery表格插件——jqGrid. 如果您在实际项目中遇到web端表格展示功能的需求,又 ...
- hashmap简单实例(个人使用经验)
一.HashMap<int,String>是错误的:因为int是基本类型,而key和value要求是对象,所以要用Integer而不是int.HashMap<String,Objec ...
- httpclient4 模拟访问网页 模拟登录 简单例子
JAVA后台模拟登录一个网站,获得一定权限后进一步操作. 所用的工具: Apache HttpComponents client 4.3版本 以下为代码: import org.apache.http ...
- Redis之个人简单理解
1.什么是redis? 在过去的几年中,NoSQL数据库一度成为高并发.海量数据存储解决方案的代名词,与之相应的产品也呈现出雨后春笋般的生机.然而在众多产品中能够脱颖而出的却屈指可数,如Redis.M ...
随机推荐
- console.read()读入的内容
今天写的特别简单的代码,大体是一个模式选择,从控制台读入一个数,然后做出相应的选择. 代码如下: using System; using System.Collections.Generic; usi ...
- 教程-Delphi源代码--后延函数
说明: 1)TTtimer控件 TTtimer控件的实质是调用WindowsAPI定时函数SetTimer和KillTimer来实现的,并简化了对WM_TIMER消息的处理过程.通过设置OnTimer ...
- A Tour of Go If with a short statement
Like for, the if statement can start with a short statement to execute before the condition. Variabl ...
- 巧用TAG属性保存对象的指针
指针的数据类型是整型,一个指针就是一个整型的数值. 所以凡整型的变量(这个整型的变量可以是声明在INI文件中,也可以是声明在函数中的)也好,对象的整型的属性也好,都可以用来存储一个指针. 但对象往往没 ...
- C#和C++中的float类型
博客搬到了fresky.github.io - Dawei XU,请各位看官挪步.最新的一篇是:C#和C++中的float类型.
- jfinal拦截器301跳转
在jfinal的handle中加入 HandlerKit.redirect301("http://10.10.3.144:8080/bbb.rar", request, respo ...
- Ajax之旅(一)--什么是Ajax
本来在学习DRP,但是无意中发现所附资料中有一些參考书籍,当中就有一个关于Ajax的,看了看,挺好的,于是决定暂停一下DRP,再次学习一下Ajax.记得第一遍学习Ajax的时候认为真的是一团雾水,看了 ...
- Android开发之IPC进程间通信-AIDL介绍及实例解析
一.IPC进程间通信 IPC是进程间通信方法的统称,Linux IPC包括以下方法,Android的进程间通信主要采用是哪些方法呢? 1. 管道(Pipe)及有名管道(named pipe):管道可用 ...
- Python之路【第二十二篇】:Django之Model操作
Django之Model操作 一.字段 AutoField(Field) - int自增列,必须填入参数 primary_key=True BigAutoField(AutoField) - bi ...
- Asp.net上传出现“超过了最大请求长度”的问题解决方法
在开发ASP.NET网站后台管理系统时,我们可能会遇到这样的问题:上传大于4M的文件时,会提示错误:错误信息如下: 1.异常详细信息:超过了最大请求长度. 2.引发异常的方法:Byte[] GetEn ...