httpClient多线程实现样例

import java.io.InterruptedIOException;
import java.net.UnknownHostException;

import org.apache.commons.httpclient.NoHttpResponseException;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
/**
 
 
 */
public class httpClientUtil {
//    public static CloseableHttpClient httpClient = HttpClients.createDefault();
    /**
 
     */

    /**
     * 线程锁
     */
     private final static Object syncLock = new Object();
     /**
      *初始化连接池
      */
     private final static PoolingHttpClientConnectionManager poolconnmanager = new PoolingHttpClientConnectionManager();
     /**
      * 设置连接数、路由数
      */
     static {
            poolconnmanager.setMaxTotal(200);
            poolconnmanager.setDefaultMaxPerRoute(150);
        }
     /**
      * 生成请求属性配置
 
      * @return
      */
     private static RequestConfig getRequestConfig() {
            return RequestConfig.custom()
                    .setSocketTimeout(10 * 1000)
                    .setConnectTimeout(10 * 1000)
                    .setConnectionRequestTimeout(10 * 1000)
                    .build();
        }
     /**
      * 生成 CloseableHttpClient

      * @return
      */
     public static CloseableHttpClient getCloseableHttpClient() {
            ConnectionKeepAliveStrategy connectionKeepAliveStrategy = (httpResponse, httpContext) -> {
                return 10 * 1000; // tomcat默认keepAliveTimeout为20s(注:小于等于服务接收端http的keepAliveTimeout即可)
            };
          //防止重复创建httpClient对象
            synchronized (syncLock){
                return HttpClients.custom()
                        .setDefaultRequestConfig(getRequestConfig())
                        .setConnectionManager(poolconnmanager)
                        .setRetryHandler(httprequestretryhandler)
                        .setKeepAliveStrategy(connectionKeepAliveStrategy)
                        .build();
            }
        }

     /**
      * http请求超时属性设置
      */
     private final static HttpRequestRetryHandler httprequestretryhandler = (exception, executionCount, context) -> {
            if (executionCount >= 3) {//重试超过3次,放弃请求
                return false;
            }
            if (exception instanceof NoHttpResponseException) {//服务器没有响应
                return true;
            }
            if (exception instanceof InterruptedIOException) {  //超时
                return false;
            }
            if (exception instanceof UnknownHostException) {
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();

            return !(request instanceof HttpEntityEnclosingRequest);
        };
    
}

/**
     * 传输上传文件
  * @param URL ​-- http://127.0.0.1:8888/projectname/lservlet?method=add
     * @param fis -- new FileInputStream(new File(filepath))
     * @return
     */public static String uploadFileNew(String URL,InputStream fis ) {
        String codeStr ="";
        CloseableHttpResponse response = null;
        try {
            HttpPost uploadFile = new HttpPost(URL);
            System.out.println("---http-----"+URL);
            uploadFile.addHeader("Accept", "application/json;charset=GBK");
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(Charset.forName("GBK"));
            // 把文件加到HTTP的post请求中。
            builder.addBinaryBody("file", fis, ContentType.APPLICATION_OCTET_STREAM,"");

            HttpEntity multipart = builder.build();
            uploadFile.setEntity(multipart);
              response =  httpClientUtil.getCloseableHttpClient().execute(uploadFile);
            HttpEntity responseEntity = response.getEntity();
            codeStr = EntityUtils.toString(responseEntity, "GBK");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return codeStr;
    }

/**
     * 接收单个文件

     * @param request
     * @param response
     */
    public void addFile(HttpServletRequest request,HttpServletResponse response) {
        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload uploader = new ServletFileUpload(factory);
        
        PrintWriter out = null;
            try {
               request.setCharacterEncoding("GBK");
           String path=request.getParameter("path");//绝对路径
        path=path.replaceAll("[\\\\]{1,10}", "/");
        path=path.replaceAll("[/]{1,10}", "/");
                out = response.getWriter();
                String paths=path.substring(0, path.lastIndexOf("/"));
                File files=new File(paths);
                if(!files.exists()) {
                    files.mkdirs();
                }
                File file = new File(path);
                if(!file.exists()){
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(file.isFile()) {
                    //获取表单信息
                    List<FileItem> fileItems = uploader.parseRequest(  request);
                    java.util.Iterator<FileItem> iter = fileItems.iterator();
                    while (iter.hasNext()) {
                        FileItem fi = iter.next();
                        if (fi.isFormField()) {
//                            String fieldName = fi.getFieldName();
//                            System.out.println("fieldName:"+fieldName);
//                            String fieldvalue = new String(fi.getString().getBytes("iso-8859-1"),"GBK");
//                            System.out.println("fieldvalue:"+fieldvalue);
                        } else {
                            //获取文件名(带后缀)
                            fi.write(new File(path));
                            fi.getOutputStream().close();
                            break;
                        }
                    }
                }
                response.setCharacterEncoding("GBK");
                out.print("true");
                out.flush();
                out.close();
            } catch (Exception e) {
                out.print("false");
                e.printStackTrace();
            }finally{
                if(out !=  null){
                    out.close();
                }
            }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用HttpClient进行多线程操作时,需要注意以下几点: 1. HttpClient实例是线程安全的,可以在多个线程中共享同一个实例。 2. 如果需要使用连接池来管理HTTP连接,则需要创建一个连接池管理器,以便在多个线程之间共享连接池。 3. 在使用多线程时,应该避免使用同步线程,因为同步线程会造成性能瓶颈。 4. HttpClient提供了异步请求功能,可以在多线程中使用异步请求来提高性能。 下面是一个使用HttpClient进行多线程操作的示例代码: ```java public class HttpClientThreadDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { CloseableHttpClient httpClient = HttpClients.createDefault(); ExecutorService executorService = Executors.newFixedThreadPool(10); List<Future<String>> futures = new ArrayList<>(); for (int i = 0; i < 100; i++) { futures.add(executorService.submit(new HttpRequestTask(httpClient))); } for (Future<String> future : futures) { System.out.println(future.get()); } httpClient.close(); executorService.shutdown(); } } class HttpRequestTask implements Callable<String> { private final CloseableHttpClient httpClient; public HttpRequestTask(CloseableHttpClient httpClient) { this.httpClient = httpClient; } @Override public String call() throws Exception { HttpGet httpGet = new HttpGet("https://www.baidu.com"); CloseableHttpResponse response = httpClient.execute(httpGet); String result = EntityUtils.toString(response.getEntity(), "UTF-8"); response.close(); return result; } } ``` 在上面的代码中,我们创建了一个大小为10的线程池,并使用HttpClient发送了100个HTTP请求。每个请求都是一个独立的线程,通过异步请求方式来实现。最后,我们将所有请求的结果输出到控制台。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值