首页>代码>Httpclient的使用实例>/HttpClient使用/Http.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ssszm;

/**
 *
 * @author seelespirit
 */
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import java.net.*;

public class Http {
    private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    // Since the Configuration has not yet been setted,
    // then an unconfigured client is returned.
    private static HttpClient httpClient = new HttpClient(connectionManager);
    private static Http http;

    public static synchronized HttpClient getClient() {
        return httpClient;
    }

    private Http(String url) {
        configureClient(url);
    }

    public static Http getInstance(String url) {
        http = new Http(url);
        return http;
    }

    private void configureClient(String url) {
        int maxThreadsTotal = 300;
        int maxThreadsPerHost = 100;
        
        HttpConnectionManagerParams params = connectionManager.getParams();
        params.setConnectionTimeout(20 * 1000);
        params.setSoTimeout(20 * 1000);
        // params.setSendBufferSize(BUFFER_SIZE);
        // params.setReceiveBufferSize(BUFFER_SIZE);
        params.setMaxTotalConnections(maxThreadsTotal);
        if (maxThreadsTotal > maxThreadsPerHost) {
        params.setDefaultMaxConnectionsPerHost(maxThreadsPerHost);
        } else {
        params.setDefaultMaxConnectionsPerHost(maxThreadsTotal);
        }

        String host = "";
        int port = 80;
        try{
            URL targetUrl = new URL(url);
            host = targetUrl.getHost();
            port = (targetUrl.getPort() == -1)?80:targetUrl.getPort();
        }catch(MalformedURLException ex){
            System.out.println("ERROR PAGE:" + url);
            System.out.println(ex.toString());
        }
        httpClient.getHostConfiguration().setHost(host,port,"http");
    }
}
最近下载更多
1358849392  LV21 2023年10月12日
xianyu091012  LV2 2023年7月14日
fdsfsffds  LV1 2022年8月4日
糙米caomi  LV1 2021年4月9日
阿昌先生  LV13 2021年1月18日
lironggang  LV38 2020年11月26日
carrot33  LV1 2020年7月30日
Call Me 采先森  LV10 2020年5月15日
xtm123  LV18 2020年3月11日
sleepcat88  LV13 2020年1月20日
最近浏览更多
雨中纸鹤  LV1 2023年12月6日
xianyu091012  LV2 2023年7月14日
fdsfsffds  LV1 2022年8月4日
mq13947193109  LV19 2022年7月5日
wangdengzhe  LV7 2022年4月6日
ssh123  LV10 2021年11月18日
我是helloworld  LV23 2021年11月17日
newhaijun  LV15 2021年7月12日
gao123qq  LV21 2021年5月7日
糙米caomi  LV1 2021年4月9日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友