Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,15 @@
<commons-codec.version>1.10</commons-codec.version>
<jetty.version>9.3.0.RC0</jetty.version>
<jedis.version>2.9.0</jedis.version>
<!-- 由于较新的3.8版本需要jdk8,故而此处采用较低版本 -->
<jodd-http.version>3.7</jodd-http.version>
</properties>

<dependencies>
<dependency>
<groupId>org.jodd</groupId>
<artifactId>jodd-http</artifactId>
<version>3.7</version>
<!-- 由于较新的3.8版本需要jdk8,故而此处采用较低版本 -->
<version>${jodd-http.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package me.chanjar.weixin.common.util.http;

import java.io.IOException;

import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;

import jodd.http.HttpConnectionProvider;
import jodd.http.ProxyInfo;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo;
import okhttp3.ConnectionPool;

/**
* Created by ecoolper on 2017/4/27.
*/
public abstract class AbstractRequestExecutor<T, E> implements RequestExecutor<T, E> {

@Override
public T execute(RequestHttp requestHttp, String uri, E data) throws WxErrorException, IOException{
if (requestHttp.getRequestHttpClient() instanceof CloseableHttpClient) {
//apache-http请求
CloseableHttpClient httpClient = (CloseableHttpClient) requestHttp.getRequestHttpClient();
HttpHost httpProxy = (HttpHost) requestHttp.getRequestHttpProxy();
return executeApache(httpClient, httpProxy, uri, data);
}
if (requestHttp.getRequestHttpClient() instanceof HttpConnectionProvider) {
//jodd-http请求
HttpConnectionProvider provider = (HttpConnectionProvider) requestHttp.getRequestHttpClient();
ProxyInfo proxyInfo = (ProxyInfo) requestHttp.getRequestHttpProxy();
return executeJodd(provider, proxyInfo, uri, data);
} else if (requestHttp.getRequestHttpClient() instanceof ConnectionPool) {
//okhttp请求
ConnectionPool pool = (ConnectionPool) requestHttp.getRequestHttpClient();
OkhttpProxyInfo proxyInfo = (OkhttpProxyInfo) requestHttp.getRequestHttpProxy();
return executeOkhttp(pool, proxyInfo, uri, data);
} else {
//TODO 这里需要抛出异常,需要优化
return null;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@
import jodd.http.HttpResponse;
import jodd.http.ProxyInfo;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.fs.FileUtils;
import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler;
import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler;
import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo;
import okhttp3.*;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
Expand All @@ -22,6 +26,8 @@
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand All @@ -31,32 +37,15 @@
*
* @author Daniel Qian
*/
public class MediaDownloadRequestExecutor implements RequestExecutor<File, String> {
public class MediaDownloadRequestExecutor extends AbstractRequestExecutor<File, String> {

private File tmpDirFile;

public MediaDownloadRequestExecutor(File tmpDirFile) {
this.tmpDirFile = tmpDirFile;
}

@Override
public File execute(RequestHttp requestHttp, String uri, String queryParam) throws WxErrorException, IOException {
if (requestHttp.getRequestHttpClient() instanceof CloseableHttpClient) {
CloseableHttpClient httpClient = (CloseableHttpClient) requestHttp.getRequestHttpClient();
HttpHost httpProxy = (HttpHost) requestHttp.getRequestHttpProxy();
return executeApache(httpClient, httpProxy, uri, queryParam);
}
if (requestHttp.getRequestHttpClient() instanceof HttpConnectionProvider) {
HttpConnectionProvider provider = (HttpConnectionProvider) requestHttp.getRequestHttpClient();
ProxyInfo proxyInfo = (ProxyInfo) requestHttp.getRequestHttpProxy();
return executeJodd(provider, proxyInfo, uri, queryParam);
} else {
//这里需要抛出异常,需要优化
return null;
}
}

private String getFileNameJodd(HttpResponse response) throws WxErrorException {
private String getFileName(HttpResponse response) throws WxErrorException {
String content = response.header("Content-disposition");
if (content == null || content.length() == 0) {
throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build());
Expand All @@ -70,15 +59,15 @@ private String getFileNameJodd(HttpResponse response) throws WxErrorException {
throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build());
}

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

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

/**
* apache-http实现方式
*
* @param httpclient
* @param httpProxy
* @param uri
Expand All @@ -95,7 +85,7 @@ private String getFileNameApache(CloseableHttpResponse response) throws WxErrorE
* @throws WxErrorException
* @throws IOException
*/
private File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, IOException {
public File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, IOException {
if (queryParam != null) {
if (uri.indexOf('?') == -1) {
uri += '?';
Expand All @@ -112,7 +102,6 @@ private File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, S
try (CloseableHttpResponse response = httpclient.execute(httpGet);
InputStream inputStream = InputStreamResponseHandler.INSTANCE
.handleResponse(response)) {

Header[] contentTypeHeader = response.getHeaders("Content-Type");
if (contentTypeHeader != null && contentTypeHeader.length > 0) {
if (contentTypeHeader[0].getValue().startsWith(ContentType.APPLICATION_JSON.getMimeType())) {
Expand All @@ -122,7 +111,7 @@ private File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, S
}
}

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

/**
* jodd-http实现方式
*
* @param provider
* @param proxyInfo
* @param uri
Expand All @@ -147,7 +137,7 @@ private File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, S
* @throws WxErrorException
* @throws IOException
*/
private File executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, String queryParam) throws WxErrorException, IOException {
public File executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, String queryParam) throws WxErrorException, IOException {
if (queryParam != null) {
if (uri.indexOf('?') == -1) {
uri += '?';
Expand All @@ -160,14 +150,15 @@ private File executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, S
provider.useProxy(proxyInfo);
}
request.withConnectionProvider(provider);

HttpResponse response = request.send();
String contentType = response.header("Content-Type");
if (contentType != null && contentType.startsWith("application/json")) {
// application/json; encoding=utf-8 下载媒体文件出错
throw new WxErrorException(WxError.fromJson(response.bodyText()));
}

String fileName = getFileNameJodd(response);
String fileName = getFileName(response);
if (StringUtils.isBlank(fileName)) {
return null;
}
Expand All @@ -178,4 +169,75 @@ private File executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, S
}


/**
* okhttp现实方式
*
* @param pool
* @param proxyInfo
* @param uri
* @param queryParam
* @return
* @throws WxErrorException
* @throws IOException
*/
public File executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, String queryParam) throws WxErrorException, IOException {
if (queryParam != null) {
if (uri.indexOf('?') == -1) {
uri += '?';
}
uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
}

OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool);
//设置代理
if (proxyInfo != null) {
clientBuilder.proxy(proxyInfo.getProxy());
}
//设置授权
clientBuilder.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword());
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
});
//得到httpClient
OkHttpClient client = clientBuilder.build();

Request request = new Request.Builder().url(uri).get().build();

Response response = client.newCall(request).execute();

String contentType = response.header("Content-Type");
if (contentType != null && contentType.startsWith("application/json")) {
// application/json; encoding=utf-8 下载媒体文件出错
throw new WxErrorException(WxError.fromJson(response.body().toString()));
}

String fileName = getFileName(response);
if (StringUtils.isBlank(fileName)) {
return null;
}

InputStream inputStream = new ByteArrayInputStream(response.body().bytes());
String[] nameAndExt = fileName.split("\\.");
return FileUtils.createTmpFile(inputStream, nameAndExt[0], nameAndExt[1], this.tmpDirFile);
}

private String getFileName(Response response) throws WxErrorException {
String content = response.header("Content-disposition");
if (content == null || content.length() == 0) {
throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build());
}

Pattern p = Pattern.compile(".*filename=\"(.*)\"");
Matcher m = p.matcher(content);
if (m.matches()) {
return m.group(1);
}
throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build());
}

}
Loading