Skip to content

Commit

Permalink
新增下载文件的方法,升级okhttp到3.14.1, 升级spring到 5.1.6
Browse files Browse the repository at this point in the history
  • Loading branch information
KeRan213539 committed Apr 11, 2019
1 parent 1e72505 commit 9814278
Show file tree
Hide file tree
Showing 5 changed files with 231 additions and 34 deletions.
60 changes: 56 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ maven引入:
<dependency>
<groupId>com.github.keran213539</groupId>
<artifactId>commonOkHttp</artifactId>
<version>0.3</version>
<version>0.4</version>
</dependency>
```

Expand Down Expand Up @@ -60,21 +60,73 @@ OkHttp,现在很火的一个Apache httpClient的替代品,说替代可能不太
### 方法说明

#### String get(String url, IAsyncCallback callback)

发送 get 请求, 有 callback为异步,callback传null为同步;异步时返回null

#### Response get(String url, Map<String, String> headerExt, IAsyncCallback4Response callback)

```
发送 get 请求并返回okhttp3.Response, 有 callback为异步,callback传null为同步;异步时返回null
```

#### String post(String url, IAsyncCallback callback)

使用无参方式发送post请求, 有 callback为异步,callback传null为同步;异步时返回null

#### String post(String url,String jsonStr, IAsyncCallback callback)
使用json方式发送post请求, 有 callback为异步,callback传null为同步;异步时返回null

#### Response post(String url,String jsonStr, Map<String, String> headerExt, IAsyncCallback4Response callback)

```
使用json方式发送post请求并返回okhttp3.Response, 有 callback为异步,callback传null为同步;异步时返回null
```



#### String post(String url, Map<String, String> prarm, IAsyncCallback callback)
使用传统参数方式发送post请求, 有 callback为异步,callback传null为同步;异步时返回null

#### <T extends UploadFileBase> String post(String url, Map<String, String> prarm, List<T> files, IAsyncCallback callback)
文件上传(支持多文件)

#### String post(String url, IAsyncCallback callback, String xmlStr)

```
使用xml方式发送post请求, 有 callback为异步,callback传null为同步;异步时返回null
```



#### String post(String url, Map<String, String> prarm, List<T> files, IAsyncCallback callback)

文件上传(支持多文件), 有 callback为异步,callback传null为同步;异步时返回null

#### byte[] download(String url, IAsyncCallback4Download callback)

```
下载文件并返回文件 byte[], 有 callback为异步,callback传null为同步;异步时返回null
```

#### byte[] download(String url, Map<String, String> headerExt, IAsyncCallback4Download callback)

```
下载文件并返回文件 byte[], 有 callback为异步,callback传null为同步;异步时返回null
```

#### Response download(Map<String, String> headerExt, IAsyncCallback4Response callback, String url)

```
下载文件并返回okhttp3.Response(可以通过response获取文件类型,文件大小, InputStream等, 有 callback为异步,callback传null为同步;异步时返回null
```

#### Response download(IAsyncCallback4Response callback, String url)

```
下载文件并返回okhttp3.Response(可以通过response获取文件类型,文件大小, InputStream等, 有 callback为异步,callback传null为同步;异步时返回null
```



## 关于测试

> Junit测试中的所有都已跑通
> JUnit的测试中删除了部分在公网没有找到合适的测试环境的代码(部分测试环境我是在本机模拟的环境),如使用自签证书的,不安全的方式,上传等,大家可以自签个证书部署为https自测
> 代码中自定义信任证书的部分,删除了一些其他环境的证书,只保留了简书的证书作为代码示例
6 changes: 3 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.github.keran213539</groupId>
<artifactId>commonOkHttp</artifactId>
<version>0.3</version>
<version>0.4</version>
<packaging>jar</packaging>
<name>commonOkHttp</name>
<description>通用OkHttp简单封装</description>
Expand Down Expand Up @@ -31,9 +31,9 @@
<skipJunitTest>true</skipJunitTest>
<project.build.jdkVersion>1.8</project.build.jdkVersion>

<spring.version>5.0.4.RELEASE</spring.version>
<spring.version>5.1.6.RELEASE</spring.version>
<commons-lang.version>2.6</commons-lang.version>
<okhttp.version>3.10.0</okhttp.version>
<okhttp.version>3.14.1</okhttp.version>
<slf4j-log4j12.version>1.7.25</slf4j-log4j12.version>
<disruptor.version>3.4.1</disruptor.version>
<junit5.version>5.1.0</junit5.version>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.springframework.util.CollectionUtils;

import com.github.keran213539.commonOkHttp.callback.IAsyncCallback;
import com.github.keran213539.commonOkHttp.callback.IAsyncCallback4Download;
import com.github.keran213539.commonOkHttp.callback.IAsyncCallback4Response;
import com.github.keran213539.commonOkHttp.utils.HttpsUtils;

Expand All @@ -37,7 +38,6 @@
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.http.HttpMethod;

/**
* @ClassName: CommonOkHttpClient
Expand Down Expand Up @@ -119,26 +119,6 @@ public String post(String url,String jsonStr, IAsyncCallback callback) {
return (String)doPost(url, null, jsonStr, callback, null, false, null);
}

public String post(HttpMethod httpMethod, String url, String jsonStr, IAsyncCallback callback) {
// RequestBody body = okhttp3.internal.Util.EMPTY_REQUEST;
// if(StringUtils.isNotBlank(postStr)) {
// body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postStr);
// } else if(!CollectionUtils.isEmpty(prarm)) {
// Builder builder = new FormBody.Builder();
// prarm.forEach((k, v) -> builder.add(k, v));
// body = builder.build();
// }
// okhttp3.Request.Builder reqBuilder = new Request.Builder().post(body).url(url);
// if(headerExt != null && headerExt.size() > 0) {
// headerExt.forEach((key, value) -> {
// reqBuilder.addHeader(key, value);
// });
// }
// Request request = reqBuilder.build();
// return sendRequest(request, isNeedResponse, callback, callback4Response);
return null;
}

/**
* @Title: post
* @Description: 使用xml方式发送post请求, 有 callback为异步,callback传null为同步;异步时返回null
Expand Down Expand Up @@ -177,7 +157,7 @@ public String post(String url, Map<String, String> prarm, IAsyncCallback callbac

/**
* @Title: post
* @Description: 文件上传(支持多文件)
* @Description: 文件上传(支持多文件), 有 callback为异步,callback传null为同步;异步时返回null
* @param url
* @param prarm
* @param files
Expand Down Expand Up @@ -264,7 +244,7 @@ private Object doPost(String url, Map<String, String> prarm, String postStr, Str
* @return
*/
private Object sendRequest(Request request, boolean isNeedResponse, IAsyncCallback callback, IAsyncCallback4Response callback4Response) {
if (callback == null) {
if (callback == null && callback4Response == null) {
// 同步
try {
Response response = okHttpClient.newCall(request).execute();
Expand Down Expand Up @@ -306,4 +286,115 @@ public void onResponse(Call call, Response response) {
return null;
}

/**
* @Title: download
* @author klw
* @Description: 下载文件, 有 callback为异步,callback传null为同步;异步时返回null
* @param url 下载地址
* @param isNeedResponse 是否需要返回okhttp3.Response
* @param headerExt 扩展的请求头信息
* @param callback 返回byte[]的回调(有callback为异步,没有为同步)
* @param callback4Response 返回okhttp3.Response 的回调
* @return
*/
private Object download(String url, boolean isNeedResponse, Map<String, String> headerExt, IAsyncCallback4Download callback, IAsyncCallback4Response callback4Response) {
okhttp3.Request.Builder reqBuilder = new Request.Builder().get().url(url);
if(headerExt != null && headerExt.size() > 0) {
headerExt.forEach((key, value) -> {
reqBuilder.addHeader(key, value);
});
}
Request request = reqBuilder.build();

if (callback == null && callback4Response == null) {
// 同步
try {
Response response = okHttpClient.newCall(request).execute();
if(isNeedResponse) {
return response;
} else {
return response.body().bytes();
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
// 异步
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if(isNeedResponse) {
callback4Response.doCallback(null);
} else {
callback.doCallback(null);
}
}

@Override
public void onResponse(Call call, Response response) {
try {
if(isNeedResponse) {
callback4Response.doCallback(response);
} else {
callback.doCallback(response.body().bytes());
}
} catch (IOException e) {
callback.doCallback(null);
}
}
});
}
return null;
}

/**
* @Title: download
* @author klw
* @Description: 下载文件并返回文件 byte[], 有 callback为异步,callback传null为同步;异步时返回null
* @param url 下载地址
* @param headerExt 扩展的请求头信息
* @param callback 返回byte[]的回调(有callback为异步,没有为同步)
* @return
*/
public byte[] download(String url, Map<String, String> headerExt, IAsyncCallback4Download callback) {
return (byte[]) download(url, false, headerExt, callback, null);
}

/**
* @Title: download
* @author klw
* @Description: 下载文件并返回okhttp3.Response(可以通过response获取文件类型,文件大小, InputStream等, 有 callback为异步,callback传null为同步;异步时返回null
* @param url 下载地址
* @param headerExt 扩展的请求头信息
* @param callback 返回okhttp3.Response 的回调
* @return
*/
public Response download(Map<String, String> headerExt, IAsyncCallback4Response callback, String url) {
return (Response) download(url, true, headerExt, null, callback);
}

/**
* @Title: download
* @author klw
* @Description: 下载文件并返回文件 byte[], 有 callback为异步,callback传null为同步;异步时返回null
* @param url 下载地址
* @param callback 返回byte[]的回调(有callback为异步,没有为同步)
* @return
*/
public byte[] download(String url, IAsyncCallback4Download callback) {
return (byte[]) download(url, false, null, callback, null);
}

/**
* @Title: download
* @author klw
* @Description: 下载文件并返回okhttp3.Response(可以通过response获取文件类型,文件大小, InputStream等, 有 callback为异步,callback传null为同步;异步时返回null
* @param url 下载地址
* @param callback 返回okhttp3.Response 的回调
* @return
*/
public Response download(IAsyncCallback4Response callback, String url) {
return (Response) download(url, true, null, null, callback);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Copyright 2018 klw([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.keran213539.commonOkHttp.callback;

/**
* @ClassName: IAsyncCallback4Download
* @Description: 异步http下载请求回调接口,支持 Lambda 表达式
* @author klw
* @date 2019-04-11 14:55:58
*/
@FunctionalInterface
public interface IAsyncCallback4Download {

/**
* @Title: doCallback
* @Description: 异步回调接口的执行方法,传入 okhttp3.Response
* @param responseBody
*/
public void doCallback(byte[] response);

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
Expand Down Expand Up @@ -70,11 +71,30 @@ public static void init() throws FileNotFoundException {
httpClientCustomCertificate = new CommonOkHttpClientBuilder().checkHostname(false).certificateFilePaths(certificateFilePaths).build();
}

@Test
public void testDownload() {
String imageUrl = "http://f.hiphotos.baidu.com/image/pic/item/71cf3bc79f3df8dcfcea3de8c311728b461028f7.jpg";
System.out.println(defaultHttps.download(imageUrl, null).length);
System.out.println(defaultHttps.download(null, imageUrl).body().contentLength());
System.out.println("==============上面是同步,下面是异步============");
defaultHttps.download(imageUrl, fileBytes -> {
System.out.println(fileBytes.length);
});

defaultHttps.download(fileBytes -> {
try {
System.out.println(fileBytes.body().bytes().length);
} catch (IOException e) {
e.printStackTrace();
}
}, imageUrl);
}

/**
* @Title: testDefaultHttps
* @Description: 测试默认https(使用CA证书)
*/
@Test
// @Test
public void testDefaultHttps() {
System.out.println(defaultHttps.get("https://www.jianshu.com/p/f5320b1e0287", null)); // 访问https
System.out.println(defaultHttps.post("https://www.baidu.com", null)); // 访问https
Expand All @@ -88,7 +108,7 @@ public void testDefaultHttps() {
* @Title: testCustomHttps
* @Description: 信任证书
*/
@Test
// @Test
public void testCustomHttps() {
System.out.println(httpClientCustomCertificate.get("https://www.jianshu.com/p/5dc612f15058", null)); // 访问https-- 不能访问
}
Expand Down Expand Up @@ -176,7 +196,7 @@ public void testPostJson() {
* @Title: testNotSafe
* @Description: 测试不安全方式访问自签证书
*/
@Test
// @Test
public void testNotSafe() {
// TODO 由于没有在外网找到合适的测试环境,所以代码已删除,实际已测过
}
Expand All @@ -187,7 +207,7 @@ public void testNotSafe() {
* @Title: afterAll4Async
* @Description: 测试异步时使用,阻塞主线程
*/
// @AfterAll
@AfterAll
public static void afterAll4Async() {
synchronized (TestWithSpring.class) {
while (true) {
Expand Down

0 comments on commit 9814278

Please sign in to comment.