1 package com.foxinmy.weixin4j.http.support.apache3;
2
3 import java.net.InetSocketAddress;
4
5 import org.apache.commons.httpclient.HttpClient;
6 import org.apache.commons.httpclient.HttpConnectionManager;
7 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
8 import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
9 import org.apache.commons.httpclient.protocol.Protocol;
10
11 import com.foxinmy.weixin4j.http.HttpParams;
12 import com.foxinmy.weixin4j.http.factory.HttpClientFactory;
13 import com.foxinmy.weixin4j.http.support.apache3.HttpComponent3.SSLProtocolSocketFactory;
14 import com.foxinmy.weixin4j.util.Consts;
15
16
17
18
19
20
21
22
23
24 public class HttpComponent3Factory extends HttpClientFactory {
25
26 private final HttpClient httpClient;
27
28 public HttpComponent3Factory() {
29 httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
30 httpClient.getParams().setHttpElementCharset(Consts.UTF_8.name());
31 httpClient.getParams().setParameter("http.protocol.uri-charset",
32 Consts.UTF_8.name());
33
34 httpClient.getParams().setContentCharset(Consts.UTF_8.name());
35 Protocol.registerProtocol("https",
36 new Protocol("https", new SSLProtocolSocketFactory(
37 HttpClientFactory.allowSSLContext()), 443));
38 }
39
40 public HttpComponent3Factory(HttpClient httpClient) {
41 this.httpClient = httpClient;
42 }
43
44 public void setHttpConnectionManager(
45 HttpConnectionManager httpConnectionManager) {
46 if (httpConnectionManager == null) {
47 throw new IllegalArgumentException(
48 "'httpConnectionManager' must not be null");
49 }
50 httpClient.setHttpConnectionManager(httpConnectionManager);
51 }
52
53 private void resolveHttpParams(HttpParams params) {
54 if (params != null) {
55 if (params.getProxy() != null) {
56 InetSocketAddress socketAddress = (InetSocketAddress) params
57 .getProxy().address();
58 httpClient.getHostConfiguration().setProxy(
59 socketAddress.getHostName(), socketAddress.getPort());
60 }
61 if (params.getSSLContext() != null) {
62 Protocol.registerProtocol("https", new Protocol("https",
63 new SSLProtocolSocketFactory(params.getSSLContext()),
64 443));
65 }
66 HttpConnectionManagerParams params_ = httpClient.getHttpConnectionManager().getParams();
67 params_.setMaxTotalConnections(params.getMaxConnections());
68 params_.setDefaultMaxConnectionsPerHost(params.getMaxConnectionsPerHost());
69 params_.setConnectionTimeout(params.getConnectTimeout());
70 }
71 }
72
73 @Override
74 public com.foxinmy.weixin4j.http.HttpClient newInstance(HttpParams params) {
75 resolveHttpParams(params);
76 return new HttpComponent3(httpClient);
77 }
78 }