`
ak23173969
  • 浏览: 28586 次
社区版块
存档分类
最新评论

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;
	}
	
}

 

分享到:
评论

相关推荐

    HttpClient 发送get和post请求

    一个简单的易学的 基于HttpClient 4.3发送psot及get请求,返回数据,适合初学者,适合初学者

    httpclient下载文件

    apache httpclient 的几个简单封装,基于httpclient4.3. 示例代码: long len = HttpUtil.download("http://localhost/upload/817.mov", "D:/test.mov"); 内部含有源码jar和lib,请翻阅 httpdownloadutil.jar

    HttpClient以及获取页面内容应用

    使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。 1.创建HttpClient对象。 HttpClient client = new HttpClient(); 2.创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;...

    java实现httpget和httppost请求httpclient-4.3.1.jar包

    利用httpclient-4.3.1.jar、httpcore-4.3.jar包,很简单的用java实现httpget和httppost请求。

    精通ANDROID 3(中文版)1/2

    15.1 闹钟管理器基本知识:设置一个简单的闹钟  15.1.1 获取闹钟管理器  15.1.2 设置闹钟时间  15.1.3 设置闹钟接收程序  15.1.4 创建适合闹钟的PendingIntent  15.1.5 设置闹钟  15.1.6 测试项目  ...

    精通Android 3 (中文版)2/2

    15.1 闹钟管理器基本知识:设置一个简单的闹钟  15.1.1 获取闹钟管理器  15.1.2 设置闹钟时间  15.1.3 设置闹钟接收程序  15.1.4 创建适合闹钟的PendingIntent  15.1.5 设置闹钟  15.1.6 测试项目  ...

    疯狂Android讲义源码

     13.3.2 使用Apache HttpClient 501  13.4 使用WebView视图  显示网页 505  13.4.1 使用WebView浏览网页 506  13.4.2 使用WebView加载HTML  代码 507  13.5 使用Web Service进行  网络编程 508  13.5.1 Web...

    疯狂Android讲义.part2

    13.3.2 使用Apache HttpClient 501 13.4 使用WebView视图显示 网页 506 13.4.1 使用WebView浏览网页 506 13.4.2 使用WebView加载HTML 代码 507 13.5 使用Web Service进行网络 编程 508 13.5.1 Web Service简介 509 ...

    疯狂Android讲义.part1

    13.3.2 使用Apache HttpClient 501 13.4 使用WebView视图显示 网页 506 13.4.1 使用WebView浏览网页 506 13.4.2 使用WebView加载HTML 代码 507 13.5 使用Web Service进行网络 编程 508 13.5.1 Web Service简介 509 ...

    Android实例代码

    7.1、使用简单图片:Drawable; Bitmap、BitmapFactory; 7.2、绘图:Canvas; Paint; Path; 7.3、图形特效处理:使用Matrix控制变换; 使用drawBitmapMesh扭曲图像; 使用Shader填充图形; 7.4、逐帧(Frame)动画:...

    疯狂Android讲义(第2版)源代码 第6章~第9章

    7.1、使用简单图片:Drawable; Bitmap、BitmapFactory; 7.2、绘图:Canvas; Paint; Path; 7.3、图形特效处理:使用Matrix控制变换; 使用drawBitmapMesh扭曲图像; 使用Shader填充图形; 7.4、逐帧(Frame)动画:...

    hadoop中文文档

    使用了Apache 的 HttpClient类库。处理以http:开头的URL。 2.3 Fetch FTP : 捉取FTP。捉取FTP的目录和文档,远程的FTP服务器必须支持 NLIST 命令。现在大多数的FTP服务器支持。 2.4 Fetch Stats :捉取的主机、端口...

    Android 开发技巧

    9.40、通过HTTPCLIENT从指定SERVER获取数据 265 9.41、通过FTP传输文件,关闭UI获得返回码 266 9.42、激活JAVASCRIPT打开内部链接 266 9.43、清空手机COOKIES 267 9.44、检查SD卡是否存在并且可以写入 267 9.45、...

    Android开发资料合集-World版!

    9.40、通过HTTPCLIENT从指定SERVER获取数据 265 9.41、通过FTP传输文件,关闭UI获得返回码 266 9.42、激活JAVASCRIPT打开内部链接 266 9.43、清空手机COOKIES 267 9.44、检查SD卡是否存在并且可以写入 267 9.45、...

    《Android应用开发揭秘》附带光盘代码.

    《Android应用开发揭秘》全部实例源代码,配合《Android应用开发揭秘》使用 前言  第一部分 准备篇  第1章 Android开发简介  1.1 Android基本概念  1.1.1 Android简介  1.1.2 Android的系统构架  1.1.3 ...

    《Android应用开发揭秘》源码

     杨丰盛,Android应用开发先驱,对Android有深入研究,实战经验极其丰富。精通Java、C、C++等语言,专注于移动通信软件开发,在机顶盒软件开发和MTK平台软件开发方面有非常深厚的积累。2007年获得中国软件行业协会...

Global site tag (gtag.js) - Google Analytics