Welcome to Yumao′s Blog.
多線程HttpClient4 Common
, 2014年07月15日 , Java Language , 评论 1 ,

跑在Web容器中的話
可以在監聽器中直接初始化HC
之後就可以用static方法進行調用
用做entity內容獲取

Code如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class ThreadHttpClient {
    private static Logger logger = Logger.getLogger(ThreadHttpClient.class);
    private static ThreadHttpClient threadhttpclient;
    private DefaultHttpClient httpclient;
    public static void load(){
        threadhttpclient = new ThreadHttpClient();
    }
    public static ThreadHttpClient getInstance() {
        if(threadhttpclient == null){
            load();
        }
        return threadhttpclient;
    }
    public void initHttp() {
        logger.info("init ThreadHttpClient...");
        //設置最大連接數
        PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
        int maxTotal = 128;
        cm.setMaxTotal(maxTotal);
        this.httpclient = new DefaultHttpClient(cm);
    }  
    public void shutHttp(){
        if(null != httpclient){
            logger.info("關閉HttpClient多線程處理");
            httpclient.getConnectionManager().shutdown();
        }
    }
    public DefaultHttpClient getHttpclient() {
        return httpclient;
    }
    public void setHttpclient(DefaultHttpClient httpclient) {
        this.httpclient = httpclient;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
public class ClientHttp {
    private static Logger logger = Logger.getLogger(ClientHttp.class);
    /**
     * 不帶參數的Get方法
     * @param  httpUrl
     *      鏈接地址
     * @return HTTP響應的字符串
     */
      
    public static String doGet(String httpUrl){
        DefaultHttpClient http=ThreadHttpClient.getInstance().getHttpclient();
        //設置超時時間
        setTimeout(http);
        //設置Get地址
        HttpGet get=new HttpGet(httpUrl);
        String entity = "";
        HttpResponse response=null;
        //開始發送請求獲取數據
        try{
            response=http.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                entity=EntityUtils.toString(response.getEntity());
            }else{
                logger.error("GET請求返回失敗");
                entity = "ErrorCode:0001";
            }
        }catch(org.apache.http.conn.ConnectTimeoutException e1){
            logger.error("HttpClient發送請求超時");
            entity = "ErrorCode:0011";
        }catch(java.net.SocketTimeoutException e2){
            logger.error("HttpClient讀取數據超時");
            entity = "ErrorCode:0100";
        }catch(Exception e){
            logger.error("GET請求發送失敗:"+e.toString());
            entity = "ErrorCode:0010";
        }finally{
            //釋放鏈接
            get.abort();
        }
        return entity;
    }
      
    /**
     * 帶參數的Get方法
     * @param  httpUrl
     *      鏈接地址
     * @param  parameters
     *      參數 x=y&z=a...
     * @return HTTP響應的字符串/出錯信息
     */
    public static String doGet(String httpUrl,String parameters){
        DefaultHttpClient http=ThreadHttpClient.getInstance().getHttpclient();
        //設置超時時間
        setTimeout(http);
        //設置Get地址
        httpUrl=httpUrl+"?"+parameters;
        HttpGet get=new HttpGet(httpUrl);
        String entity = "";
        HttpResponse response=null;
        //開始發送請求獲取數據
        try{
            response=http.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                entity=EntityUtils.toString(response.getEntity());
            }else{
                logger.error("GET請求返回失敗");
                entity = "ErrorCode:0001";
            }
        }catch(org.apache.http.conn.ConnectTimeoutException e1){
            logger.error("HttpClient發送請求超時");
            entity = "ErrorCode:0011";
        }catch(java.net.SocketTimeoutException e2){
            logger.error("HttpClient讀取數據超時");
            entity = "ErrorCode:0100";
        }catch(Exception e){
            logger.error("GET請求發送失敗:"+e.toString());
            entity = "ErrorCode:0010";
        }finally{
            //釋放鏈接
            get.abort();
        }
        return entity;
    }
      
    /**
     * 帶參數的Get方法
     * @param  httpUrl
     *      鏈接地址
     * @param  parameters 
     *      類型:Map
     * @return HTTP響應的字符串
     */
    public static String doGet(String httpUrl,Map<String,String> parameters){
        DefaultHttpClient http=ThreadHttpClient.getInstance().getHttpclient();
        //設置超時時間
        setTimeout(http);
        //設置Get地址
        httpUrl=httpUrl+"?";
        Iterator it = parameters.entrySet().iterator();
        int count=0;
        while(it.hasNext()){
            if(count==0){
                count++;
            }else{
                httpUrl=httpUrl+"&";
            }
            Map.Entry m=(Map.Entry)it.next();
            httpUrl=httpUrl+m.getKey()+"="+m.getValue();
        }
        logger.info("請求地址組織完畢 : " + httpUrl);
        HttpGet get=new HttpGet(httpUrl);
        String entity = "";
        HttpResponse response=null;
        //開始發送請求獲取數據
        try{
            response=http.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                entity=EntityUtils.toString(response.getEntity());
            }else{
                logger.error("GET請求返回失敗");
                entity = "ErrorCode:0001";
            }
        }catch(org.apache.http.conn.ConnectTimeoutException e1){
            logger.error("HttpClient發送請求超時");
            entity = "ErrorCode:0011";
        }catch(java.net.SocketTimeoutException e2){
            logger.error("HttpClient讀取數據超時");
            entity = "ErrorCode:0100";
        }catch(Exception e){
            logger.error("GET請求發送失敗:"+e.toString());
            entity = "ErrorCode:0010";
        }finally{
            //釋放鏈接
            get.abort();
        }
        return entity;
    }
      
    /**
     * 帶參數的Post方法
     * @param  httpUrl
     *      鏈接地址
     * @param  parameters
     *      參數 x=y&z=a...
     * @param  StrCode 
     *      字符編碼
     * @return HTTP響應的字符串
     */
    public static String doPost(String httpUrl,String parameters,String StrCode){
        DefaultHttpClient http=ThreadHttpClient.getInstance().getHttpclient();
        //設置超時時間
        setTimeout(http);
        //設置Post地址
        HttpPost post=new HttpPost(httpUrl);
        //組織Post內容
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        String para[]=parameters.split("&");
        for(int i=0;i<para.length;i++){
            params.add(new BasicNameValuePair(para[i].substring(0,para[i].indexOf("=")),para[i].substring(para[i].indexOf("=")+1)));
        }
        //發送請求
        String entity = "";
        HttpResponse response=null;
        //開始發送請求獲取數據
        try{
            post.setEntity(new UrlEncodedFormEntity(params,StrCode));
            response=http.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                entity=EntityUtils.toString(response.getEntity());
            }else{
                logger.error("POST請求返回失敗");
                entity = "ErrorCode:0001";
            }
        }catch(org.apache.http.conn.ConnectTimeoutException e1){
            logger.error("HttpClient發送請求超時");
            entity = "ErrorCode:0011";
        }catch(java.net.SocketTimeoutException e2){
            logger.error("HttpClient讀取數據超時");
            entity = "ErrorCode:0100";
        }catch(Exception e){
            logger.error("POST請求發送失敗:"+e.toString());
            entity = "ErrorCode:0010";
        }finally{
            //釋放鏈接
            post.abort();
        }
        return entity;
    }
      
    /**
     * 帶參數的Post方法
     * @param  httpUrl  鏈接地址
     * @param  parameters 參數Map
     * @param  StrCode  字符編碼
     * @return HTTP響應的字符串
     */
    public static String doPost(String httpUrl,Map<String,String> parameters,String StrCode){
        DefaultHttpClient http=ThreadHttpClient.getInstance().getHttpclient();
        //設置超時時間
        setTimeout(http);  
        //設置Post地址
        HttpPost post=new HttpPost(httpUrl);
        //組織Post內容
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Iterator it = parameters.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry m=(Map.Entry)it.next();
            params.add(new BasicNameValuePair(m.getKey()+"",m.getValue()+""));
        }
        //發送請求
        String entity = "";
        HttpResponse response=null;
        //開始發送請求獲取數據
        try{
            post.setEntity(new UrlEncodedFormEntity(params,StrCode));
            response=http.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                entity=EntityUtils.toString(response.getEntity());
            }else{
                logger.error("POST請求返回失敗");
                entity = "ErrorCode:0001";
            }
        }catch(org.apache.http.conn.ConnectTimeoutException e1){
            logger.error("HttpClient發送請求超時");
            entity = "ErrorCode:0011";
        }catch(java.net.SocketTimeoutException e2){
            logger.error("HttpClient讀取數據超時");
            entity = "ErrorCode:0100";
        }catch(Exception e){
            logger.error("POST請求發送失敗:"+e.toString());
            entity = "ErrorCode:0010";
        }finally{
            //釋放鏈接
            post.abort();
        }
        return entity;
    }
    public static void setTimeout(DefaultHttpClient http){
        //設置打開鏈接超時時間
        http.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
        //設置讀取數據超時超時時間
        http.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
    }
}
关键字:, ,