Skip to content

Commit 48d6f10

Browse files
crskypbinarywang
authored andcommitted
提取公共代码、实现okhttp请求方式 (binarywang#199)
1、提取了公共代码,添加AbstractWxMPService、AbstractWxCPService类 2、实现了okhttp请求方式
1 parent 2029cd0 commit 48d6f10

32 files changed

+2199
-2448
lines changed

pom.xml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,14 +107,15 @@
107107
<commons-codec.version>1.10</commons-codec.version>
108108
<jetty.version>9.3.0.RC0</jetty.version>
109109
<jedis.version>2.9.0</jedis.version>
110+
<!-- 由于较新的3.8版本需要jdk8,故而此处采用较低版本 -->
111+
<jodd-http.version>3.7</jodd-http.version>
110112
</properties>
111113

112114
<dependencies>
113115
<dependency>
114116
<groupId>org.jodd</groupId>
115117
<artifactId>jodd-http</artifactId>
116-
<version>3.7</version>
117-
<!-- 由于较新的3.8版本需要jdk8,故而此处采用较低版本 -->
118+
<version>${jodd-http.version}</version>
118119
</dependency>
119120
<dependency>
120121
<groupId>com.squareup.okhttp3</groupId>
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package me.chanjar.weixin.common.util.http;
2+
3+
import java.io.IOException;
4+
5+
import org.apache.http.HttpHost;
6+
import org.apache.http.impl.client.CloseableHttpClient;
7+
8+
import jodd.http.HttpConnectionProvider;
9+
import jodd.http.ProxyInfo;
10+
import me.chanjar.weixin.common.exception.WxErrorException;
11+
import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo;
12+
import okhttp3.ConnectionPool;
13+
14+
/**
15+
* Created by ecoolper on 2017/4/27.
16+
*/
17+
public abstract class AbstractRequestExecutor<T, E> implements RequestExecutor<T, E> {
18+
19+
@Override
20+
public T execute(RequestHttp requestHttp, String uri, E data) throws WxErrorException, IOException{
21+
if (requestHttp.getRequestHttpClient() instanceof CloseableHttpClient) {
22+
//apache-http请求
23+
CloseableHttpClient httpClient = (CloseableHttpClient) requestHttp.getRequestHttpClient();
24+
HttpHost httpProxy = (HttpHost) requestHttp.getRequestHttpProxy();
25+
return executeApache(httpClient, httpProxy, uri, data);
26+
}
27+
if (requestHttp.getRequestHttpClient() instanceof HttpConnectionProvider) {
28+
//jodd-http请求
29+
HttpConnectionProvider provider = (HttpConnectionProvider) requestHttp.getRequestHttpClient();
30+
ProxyInfo proxyInfo = (ProxyInfo) requestHttp.getRequestHttpProxy();
31+
return executeJodd(provider, proxyInfo, uri, data);
32+
} else if (requestHttp.getRequestHttpClient() instanceof ConnectionPool) {
33+
//okhttp请求
34+
ConnectionPool pool = (ConnectionPool) requestHttp.getRequestHttpClient();
35+
OkhttpProxyInfo proxyInfo = (OkhttpProxyInfo) requestHttp.getRequestHttpProxy();
36+
return executeOkhttp(pool, proxyInfo, uri, data);
37+
} else {
38+
//TODO 这里需要抛出异常,需要优化
39+
return null;
40+
}
41+
}
42+
43+
}

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java

Lines changed: 89 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@
55
import jodd.http.HttpResponse;
66
import jodd.http.ProxyInfo;
77
import me.chanjar.weixin.common.bean.result.WxError;
8+
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
89
import me.chanjar.weixin.common.exception.WxErrorException;
910
import me.chanjar.weixin.common.util.fs.FileUtils;
1011
import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler;
1112
import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler;
13+
import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo;
14+
import okhttp3.*;
15+
1216
import org.apache.commons.lang3.StringUtils;
1317
import org.apache.http.Header;
1418
import org.apache.http.HttpHost;
@@ -22,6 +26,8 @@
2226
import java.io.File;
2327
import java.io.IOException;
2428
import java.io.InputStream;
29+
import java.net.InetSocketAddress;
30+
import java.net.Proxy;
2531
import java.util.regex.Matcher;
2632
import java.util.regex.Pattern;
2733

@@ -31,32 +37,15 @@
3137
*
3238
* @author Daniel Qian
3339
*/
34-
public class MediaDownloadRequestExecutor implements RequestExecutor<File, String> {
40+
public class MediaDownloadRequestExecutor extends AbstractRequestExecutor<File, String> {
3541

3642
private File tmpDirFile;
3743

3844
public MediaDownloadRequestExecutor(File tmpDirFile) {
3945
this.tmpDirFile = tmpDirFile;
4046
}
4147

42-
@Override
43-
public File execute(RequestHttp requestHttp, String uri, String queryParam) throws WxErrorException, IOException {
44-
if (requestHttp.getRequestHttpClient() instanceof CloseableHttpClient) {
45-
CloseableHttpClient httpClient = (CloseableHttpClient) requestHttp.getRequestHttpClient();
46-
HttpHost httpProxy = (HttpHost) requestHttp.getRequestHttpProxy();
47-
return executeApache(httpClient, httpProxy, uri, queryParam);
48-
}
49-
if (requestHttp.getRequestHttpClient() instanceof HttpConnectionProvider) {
50-
HttpConnectionProvider provider = (HttpConnectionProvider) requestHttp.getRequestHttpClient();
51-
ProxyInfo proxyInfo = (ProxyInfo) requestHttp.getRequestHttpProxy();
52-
return executeJodd(provider, proxyInfo, uri, queryParam);
53-
} else {
54-
//这里需要抛出异常,需要优化
55-
return null;
56-
}
57-
}
58-
59-
private String getFileNameJodd(HttpResponse response) throws WxErrorException {
48+
private String getFileName(HttpResponse response) throws WxErrorException {
6049
String content = response.header("Content-disposition");
6150
if (content == null || content.length() == 0) {
6251
throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build());
@@ -70,15 +59,15 @@ private String getFileNameJodd(HttpResponse response) throws WxErrorException {
7059
throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build());
7160
}
7261

73-
private String getFileNameApache(CloseableHttpResponse response) throws WxErrorException {
62+
private String getFileName(CloseableHttpResponse response) throws WxErrorException {
7463
Header[] contentDispositionHeader = response.getHeaders("Content-disposition");
75-
if(contentDispositionHeader == null || contentDispositionHeader.length == 0){
64+
if (contentDispositionHeader == null || contentDispositionHeader.length == 0) {
7665
throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build());
7766
}
7867

7968
Pattern p = Pattern.compile(".*filename=\"(.*)\"");
8069
Matcher m = p.matcher(contentDispositionHeader[0].getValue());
81-
if(m.matches()){
70+
if (m.matches()) {
8271
return m.group(1);
8372
}
8473
throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build());
@@ -87,6 +76,7 @@ private String getFileNameApache(CloseableHttpResponse response) throws WxErrorE
8776

8877
/**
8978
* apache-http实现方式
79+
*
9080
* @param httpclient
9181
* @param httpProxy
9282
* @param uri
@@ -95,7 +85,7 @@ private String getFileNameApache(CloseableHttpResponse response) throws WxErrorE
9585
* @throws WxErrorException
9686
* @throws IOException
9787
*/
98-
private File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, IOException {
88+
public File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, IOException {
9989
if (queryParam != null) {
10090
if (uri.indexOf('?') == -1) {
10191
uri += '?';
@@ -112,7 +102,6 @@ private File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, S
112102
try (CloseableHttpResponse response = httpclient.execute(httpGet);
113103
InputStream inputStream = InputStreamResponseHandler.INSTANCE
114104
.handleResponse(response)) {
115-
116105
Header[] contentTypeHeader = response.getHeaders("Content-Type");
117106
if (contentTypeHeader != null && contentTypeHeader.length > 0) {
118107
if (contentTypeHeader[0].getValue().startsWith(ContentType.APPLICATION_JSON.getMimeType())) {
@@ -122,7 +111,7 @@ private File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, S
122111
}
123112
}
124113

125-
String fileName = getFileNameApache(response);
114+
String fileName = getFileName(response);
126115
if (StringUtils.isBlank(fileName)) {
127116
return null;
128117
}
@@ -139,6 +128,7 @@ private File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, S
139128

140129
/**
141130
* jodd-http实现方式
131+
*
142132
* @param provider
143133
* @param proxyInfo
144134
* @param uri
@@ -147,7 +137,7 @@ private File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, S
147137
* @throws WxErrorException
148138
* @throws IOException
149139
*/
150-
private File executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, String queryParam) throws WxErrorException, IOException {
140+
public File executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, String queryParam) throws WxErrorException, IOException {
151141
if (queryParam != null) {
152142
if (uri.indexOf('?') == -1) {
153143
uri += '?';
@@ -160,14 +150,15 @@ private File executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, S
160150
provider.useProxy(proxyInfo);
161151
}
162152
request.withConnectionProvider(provider);
153+
163154
HttpResponse response = request.send();
164155
String contentType = response.header("Content-Type");
165156
if (contentType != null && contentType.startsWith("application/json")) {
166157
// application/json; encoding=utf-8 下载媒体文件出错
167158
throw new WxErrorException(WxError.fromJson(response.bodyText()));
168159
}
169160

170-
String fileName = getFileNameJodd(response);
161+
String fileName = getFileName(response);
171162
if (StringUtils.isBlank(fileName)) {
172163
return null;
173164
}
@@ -178,4 +169,75 @@ private File executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, S
178169
}
179170

180171

172+
/**
173+
* okhttp现实方式
174+
*
175+
* @param pool
176+
* @param proxyInfo
177+
* @param uri
178+
* @param queryParam
179+
* @return
180+
* @throws WxErrorException
181+
* @throws IOException
182+
*/
183+
public File executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, String queryParam) throws WxErrorException, IOException {
184+
if (queryParam != null) {
185+
if (uri.indexOf('?') == -1) {
186+
uri += '?';
187+
}
188+
uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
189+
}
190+
191+
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool);
192+
//设置代理
193+
if (proxyInfo != null) {
194+
clientBuilder.proxy(proxyInfo.getProxy());
195+
}
196+
//设置授权
197+
clientBuilder.authenticator(new Authenticator() {
198+
@Override
199+
public Request authenticate(Route route, Response response) throws IOException {
200+
String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword());
201+
return response.request().newBuilder()
202+
.header("Authorization", credential)
203+
.build();
204+
}
205+
});
206+
//得到httpClient
207+
OkHttpClient client = clientBuilder.build();
208+
209+
Request request = new Request.Builder().url(uri).get().build();
210+
211+
Response response = client.newCall(request).execute();
212+
213+
String contentType = response.header("Content-Type");
214+
if (contentType != null && contentType.startsWith("application/json")) {
215+
// application/json; encoding=utf-8 下载媒体文件出错
216+
throw new WxErrorException(WxError.fromJson(response.body().toString()));
217+
}
218+
219+
String fileName = getFileName(response);
220+
if (StringUtils.isBlank(fileName)) {
221+
return null;
222+
}
223+
224+
InputStream inputStream = new ByteArrayInputStream(response.body().bytes());
225+
String[] nameAndExt = fileName.split("\\.");
226+
return FileUtils.createTmpFile(inputStream, nameAndExt[0], nameAndExt[1], this.tmpDirFile);
227+
}
228+
229+
private String getFileName(Response response) throws WxErrorException {
230+
String content = response.header("Content-disposition");
231+
if (content == null || content.length() == 0) {
232+
throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build());
233+
}
234+
235+
Pattern p = Pattern.compile(".*filename=\"(.*)\"");
236+
Matcher m = p.matcher(content);
237+
if (m.matches()) {
238+
return m.group(1);
239+
}
240+
throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build());
241+
}
242+
181243
}

0 commit comments

Comments
 (0)