使用httpClient可模拟请求Url获取资源,使用单线程的请求速度上会有一定的限制,参考了Apache给出的例子,自己做了测试实现多线程并发请求,以下代码需要HttpClient 4.2的包,可以在http://hc.apache.org/downloads.cgi下载

1、并发请求

package generate.httpclient;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils; public class ThreadPoolHttpClient {
// 线程池
private ExecutorService exe = null;
// 线程池的容量
private static final int POOL_SIZE = 20;
private HttpClient client = null;
String[] urls=null;
public ThreadPoolHttpClient(String[] urls){
this.urls=urls;
}
public void test() throws Exception {
exe = Executors.newFixedThreadPool(POOL_SIZE);
HttpParams params =new BasicHttpParams();
/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(params, 1000);
/* 连接超时 */
HttpConnectionParams.setConnectionTimeout(params, 2000);
/* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 4000);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); //ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
PoolingClientConnectionManager cm=new PoolingClientConnectionManager(schemeRegistry);
cm.setMaxTotal(10);
final HttpClient httpClient = new DefaultHttpClient(cm,params); // URIs to perform GETs on
final String[] urisToGet = urls;
/* 有多少url创建多少线程,url多时机子撑不住
// create a thread for each URI
GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i < threads.length; i++) {
HttpGet httpget = new HttpGet(urisToGet[i]);
threads[i] = new GetThread(httpClient, httpget);
}
// start the threads
for (int j = 0; j < threads.length; j++) {
threads[j].start();
} // join the threads,等待所有请求完成
for (int j = 0; j < threads.length; j++) {
threads[j].join();
}
使用线程池*/
for (int i = 0; i < urisToGet.length; i++) {
final int j=i;
System.out.println(j);
HttpGet httpget = new HttpGet(urisToGet[i]);
exe.execute( new GetThread(httpClient, httpget));
} //创建线程池,每次调用POOL_SIZE
/*
for (int i = 0; i < urisToGet.length; i++) {
final int j=i;
System.out.println(j);
exe.execute(new Thread() {
@Override
public void run() {
this.setName("threadsPoolClient"+j); try {
this.sleep(100);
System.out.println(j);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} HttpGet httpget = new HttpGet(urisToGet[j]);
new GetThread(httpClient, httpget).get();
} });
} */
//exe.shutdown();
System.out.println("Done");
}
static class GetThread extends Thread{ private final HttpClient httpClient;
private final HttpContext context;
private final HttpGet httpget; public GetThread(HttpClient httpClient, HttpGet httpget) {
this.httpClient = httpClient;
this.context = new BasicHttpContext();
this.httpget = httpget;
}
@Override
public void run(){
this.setName("threadsPoolClient");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
get();
} public void get() {
try {
HttpResponse response = this.httpClient.execute(this.httpget, this.context);
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println(this.httpget.getURI()+": status"+response.getStatusLine().toString());
}
// ensure the connection gets released to the manager
EntityUtils.consume(entity);
} catch (Exception ex) {
this.httpget.abort();
}finally{
httpget.releaseConnection();
}
}
}
}

并发请求

2、多线程异步请求

package generate.httpclient;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch; import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.nio.reactor.IOReactorException; public class AsynClient{
/**
* @param args
* @throws IOReactorException
* @throws InterruptedException
*/
private List<String> urls;
private HandlerFailThread failHandler;
public AsynClient(List<String> list){
failHandler=new HandlerFailThread();
urls=list;
}
public Map<String,String> asynGet() throws IOReactorException,
InterruptedException {
final HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
httpclient.start();
int urlLength=urls.size();
HttpGet[] requests = new HttpGet[urlLength];
int i=0;
for(String url : urls){
requests[i]=new HttpGet(url);
i++;
}
final CountDownLatch latch = new CountDownLatch(requests.length);
final Map<String, String> responseMap=new HashMap<String, String>();
try {
for (final HttpGet request : requests) {
httpclient.execute(request, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) {
latch.countDown();
responseMap.put(request.getURI().toString(), response.getStatusLine().toString());
try {
System.out.println(request.getRequestLine() + "->"
+ response.getStatusLine()+"->");
//+readInputStream(response.getEntity().getContent()) } catch (IllegalStateException e) {
failHandler.putFailUrl(request.getURI().toString(),
response.getStatusLine().toString());
e.printStackTrace();
} catch (Exception e) {
failHandler.putFailUrl(request.getURI().toString(),
response.getStatusLine().toString());
e.printStackTrace();
}
} public void failed(final Exception ex) {
latch.countDown();
ex.printStackTrace();
failHandler.putFailUrl(request.getURI().toString(),
ex.getMessage());
} public void cancelled() {
latch.countDown();
} });
}
System.out.println("Doing...");
} finally {
latch.await();
httpclient.shutdown();
}
System.out.println("Done");
failHandler.printFailUrl();
return responseMap;
}
private String readInputStream(InputStream input) throws IOException{
byte[] buffer = new byte[128];
int len = 0;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
while((len = input.read(buffer)) >= 0) {
bytes.write(buffer, 0, len);
}
return bytes.toString();
}
/**
* Test
* @param args
*/
public static void main(String[] args) {
List<String> urls=new ArrayList<String>();
urls.add("http://127.0.0.1/examples/servlets/");
urls.add("http://127.0.0.1/examples/servlets/");
urls.add("http://127.0.0.1/examples/servlets/");
for(int i=0;i<10;i++){
urls.addAll(urls);
}
System.out.println(urls.size());
AsynClient client=new AsynClient(urls);
try {
client.asynGet();
} catch (IOReactorException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("done");
}
}

多线程异步请求

3、创建一个线程记录失败的请求

package generate.httpclient;

import java.util.HashMap;
import java.util.Map; public class HandlerFailThread extends Thread{
Map<String, String> failUrl=new HashMap<String, String>();
public void putFailUrl(String url,String status){
synchronized (failUrl) {
failUrl.put(url,status);
}
}
@Override
public void run() {
while(true){ }
}
public void printFailUrl(){
for(Map.Entry<String, String> m: failUrl.entrySet()){
System.out.println("****fail:url:"+m.getKey()+ " code :"+m.getValue());
}
}
}

线程记录失败的请求

异步请求,也可通过pool管理,例如

ConnectingIOReactor nio=new DefaultConnectingIOReactor();
  PoolingClientAsyncConnectionManager manager=new PoolingClientAsyncConnectionManager(nio);
  manager.setMaxTotal(1000);
  manager.setDefaultMaxPerRoute(100);
  HttpParams params=new BasicHttpParams();
  /* 连接超时 */ 
  HttpConnectionParams.setConnectionTimeout(params, 10000); 
  /* 请求超时 */
  HttpConnectionParams.setSoTimeout(params, 60*1000);
  DefaultHttpAsyncClient.setDefaultHttpParams(params);
  final HttpAsyncClient httpclient = new DefaultHttpAsyncClient(manager);
  httpclient.start();

HttpClient相关可参看,里面有很多说明与例子

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html

 

httpClient多线程请求的更多相关文章

  1. httpclient 多线程请求

    线程请求执行 当配备一个线程池管理器后,如PollingClientConnectionManager,HttpClient就能使用执行着的多线程去执行并行的多请求. PollingClientCon ...

  2. 使用HttpClient发送请求、接收响应

    使用HttpClient发送请求.接收响应很简单,只要如下几步即可. 1.创建HttpClient对象.  CloseableHttpClient httpclient = HttpClients.c ...

  3. Java HttpClient伪造请求之简易封装满足HTTP以及HTTPS请求

    HttpClient简介 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 jav ...

  4. 使用HttpClient发送请求接收响应

    1.一般需要如下几步:(1) 创建HttpClient对象.(2)创建请求方法的实例,并指定请求URL.如果需要发送GET请求,创建HttpGet对象:如果需要发送POST请求,创建HttpPost对 ...

  5. 使用httpclient post请求中文乱码解决办法

    使用httpclient post请求中文乱码解决办法   在使用httpclient发送post请求的时候,接收端中文乱码问题解决. 正文: 我们都知道,一般情况下使用post请求是不会出现中文乱码 ...

  6. java HttpClient POST请求

    一个简单的HttpClient POST 请求实例 package com.httpclientget; import java.awt.List; import java.util.ArrayLis ...

  7. java HttpClient GET请求

    HttpClient GET请求小实例,先简单记录下. package com.httpclientget; import java.io.IOException; import org.apache ...

  8. HttpClient get和HttpClient Post请求的方式获取服务器的返回数据

    1.转自:https://blog.csdn.net/alinshen/article/details/78221567?utm_source=blogxgwz4 /*  * 演示通过HttpClie ...

  9. 给HttpClient添加请求头(HttpClientFactory)

    前言 在微服务的大环境下,会出现这个服务调用这个接口,那个接口的情况.假设出了问题,需要排查的时候,我们要怎么关联不同服务之间的调用情况呢?换句话就是说,这个请求的结果不对,看看是那里出了问题. 最简 ...

随机推荐

  1. 西门子MES解决方案SIMATIC IT在乳制品行业小试牛刀

    竞争的白热化,紧缩的产品利润,食品安全保障,越来越苛刻的法规要求和全球化的市场与品牌维持的重要性对乳品行业的企业提出了更高的要求,实施 MES将是企业唯一的出路. 自从“十一五”制造业信息化为MES正 ...

  2. 2016/09/21 java split用法

    public String[] split(String regex) 默认limit为0 public String[] split(String regex, int limit) 当limit& ...

  3. STM32F4_TIM输出PWM波形(可调频率、占空比)

    Ⅰ.概述 上一篇文章关于STM32基本的计数原理明白之后,该文章是在其基础上进行拓展,讲述关于STM32比较输出的功能,以输出PWM波形为实例来讲述. 提供实例工程中比较实用的函数:只需要调用该函数, ...

  4. 11.python中的元组

    在学习什么是元组之前,我们先来看看如何创建一个元组对象: a = ('abc',123) b = tuple(('def',456)) print a print b

  5. instanceof、==号、Objetc类

    1)instanceof: 判断某个对象是否为某个类的实例,注意多态的运用,一个父类引用指向子类的对象,根据继承,子类就是父类,所以子类也可以看做是父类的一个实例.  形式:引用 instanceof ...

  6. Oracle Imp and Exp (导入和导出) 数据 工具使用

    Oracle 提供两个工具imp.exe 和exp.exe分别用于导入和导出数据.这两个工具位于Oracle_home/bin目录下. 导入数据exp 1 将数据库ATSTestDB完全导出,用户名s ...

  7. hdu 4217 Data Structure?/treap

    原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=4217 可用线段树写,效率要高点. 这道题以前用c语言写的treap水过了.. 现在接触了c++重写一遍 ...

  8. iOS高级编程之XML,JSON数据解析

    解析的基本概念 所谓“解析”:从事先规定好的格式串中提取数据 解析的前提:提前约定好格式.数据提供方按照格式提供数据.数据获取方按照格式获取数据 iOS开发常见的解析:XML解析.JSON解析 一.X ...

  9. [shell实例]——用脚本实现向多台服务器批量复制文件(nmap、scp)

    练习环境: (1)所有服务器将防火墙和selinux关闭 (2)所有服务器的root密码设置为aixocm (3)所有服务器都为10.0.100.*网段,并保证能够和其它主机通信 (4)所有服务器确保 ...

  10. 微软职位内部推荐-SDEII

    微软近期Open的职位: Software Engineer II for Customer Experience (Level 62+) Location: Suzhou Contact Perso ...