okhttp同步异步下载文件,与http请求工具类
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.8.0</version> </dependency>
ok: http: connect-timeout: 30 read-timeout: 30 write-timeout: 30 keep-alive-duration: 60 max-idle-connections: 3
import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import okhttp3.ConnectionPool; import okhttp3.OkHttpClient; @Configuration public class OkHttpConfig { @Value("${ok.http.connect-timeout}") private Integer connectTimeout; @Value("${ok.http.read-timeout}") private Integer readTimeout; @Value("${ok.http.write-timeout}") private Integer writeTimeout; @Value("${ok.http.max-idle-connections}") private Integer maxIdleConnections; @Value("${ok.http.keep-alive-duration}") private Long keepAliveDuration; @Bean public OkHttpClient okHttpClient() { return new OkHttpClient.Builder() .sslSocketFactory(sslSocketFactory(), x509TrustManager()) // 是否开启缓存 .retryOnConnectionFailure(false) //连接池 .connectionPool(pool()) .connectTimeout(connectTimeout, TimeUnit.SECONDS) .readTimeout(readTimeout, TimeUnit.SECONDS) .writeTimeout(writeTimeout,TimeUnit.SECONDS) .hostnameVerifier((hostname, session) -> true) // 设置代理 // .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888))) // 拦截器 // .addInterceptor() .build(); } @Bean public X509TrustManager x509TrustManager() { return new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; } @Bean public SSLSocketFactory sslSocketFactory() { try { // 信任任何链接 SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom()); return sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException | KeyManagementException e) { e.printStackTrace(); } return null; } @Bean public ConnectionPool pool() { return new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS); } }
//异步下载 downloadUtil.downloadByAsync("http://xxx.xxx.xxx/abc.zip", "e://test//", "abc.zip", new DownloadUtil.OnDownloadListener() { @Override public void onDownloadSuccess(File file) { log.info("下载完成"); } @Override public void onDownloading(int progress) { log.info("下载进行中"+progress); // progressDialog.setProgress(progress); } @Override public void onDownloadFailed(Exception e) { //下载异常进行相关提示操作 log.error("下载出错", e); } }); //同步下载 downloadUtil.downloadBySysc("http://xxx.xxx.xxx.xxx/abc.zip", "e://test//", "abc.zip");
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okio.BufferedSink; import okio.Okio; import okio.Sink; /** * 文件下载工具类(单例模式) */ @Component @Slf4j public class DownloadUtil { @Autowired private OkHttpClient okHttpClient; /** * @param url 下载连接 * @param destFileDir 下载的文件储存目录 * @param destFileName 下载文件名称,后面记得拼接后缀,否则手机没法识别文件类型 * @param listener 下载监听 */ public interface OnDownloadListener{ /** * 下载成功之后的文件 */ void onDownloadSuccess(File file); /** * 下载进度 */ void onDownloading(int progress); /** * 下载异常信息 */ void onDownloadFailed(Exception e); } public void downloadBySink(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) { Request request = new Request.Builder() .url(url) .build(); //异步请求 okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 下载失败监听回调 listener.onDownloadFailed(e); } @Override public void onResponse(Call call, Response response) throws IOException { //储存下载文件的目录 File dir = new File(destFileDir); if (!dir.exists()) { dir.mkdirs(); } File file = new File(dir, destFileName); Sink sink = null; BufferedSink bufferedSink = null; try { sink = Okio.sink(file); bufferedSink = Okio.buffer(sink); bufferedSink.writeAll(response.body().source()); bufferedSink.close(); listener.onDownloadSuccess(file); } catch (Exception e) { log.error("error:{}", e); listener.onDownloadFailed(e); }finally { if(bufferedSink != null){ bufferedSink.close(); } } } }); } public void downloadByAsync(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) { Request request = new Request.Builder() .url(url) .build(); //异步请求 okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 下载失败监听回调 listener.onDownloadFailed(e); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream is = null; byte[] buf = new byte[4096]; int len = 0; FileOutputStream fos = null; // 储存下载文件的目录 File dir = new File(destFileDir); if (!dir.exists()) { dir.mkdirs(); } File file = new File(dir, destFileName); try { is = response.body().byteStream(); fos = new FileOutputStream(file); int size = 0; long total = response.body().contentLength(); while ((size = is.read(buf)) != -1) { len += size; fos.write(buf, 0, size); int process = (int) Math.floor(((double) len / total) * 100); // 控制台打印文件下载的百分比情况 listener.onDownloading(process); } fos.flush(); // 下载完成 listener.onDownloadSuccess(file); } catch (Exception e) { log.error("error:{}", e); listener.onDownloadFailed(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }); } public void downloadBySysc(final String url, final String destFileDir, final String destFileName) { Request request = new Request.Builder().url(url).build(); // 异步请求 Response response = null; InputStream is = null; byte[] buf = new byte[4096]; int len = 0; FileOutputStream fos = null; try { response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { // 储存下载文件的目录 File dir = new File(destFileDir); if (!dir.exists()) { dir.mkdirs(); } File file = new File(dir, destFileName); is = response.body().byteStream(); fos = new FileOutputStream(file); int size = 0; long total = response.body().contentLength(); while ((size = is.read(buf)) != -1) { len += size; fos.write(buf, 0, size); int process = (int) Math.floor(((double) len / total) * 100); log.info("下载进度" + process); } fos.flush(); } else { throw new IOException("Unexpected code " + response); } } catch (IOException e) { log.error("error:{}", e); e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
import java.util.Map; import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; import okhttp3.FormBody; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; @Slf4j @Component public class OkHttpUtil { private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final MediaType XML = MediaType.parse("application/xml; charset=utf-8"); @Autowired private OkHttpClient okHttpClient; /** * get 请求 * @param url 请求url地址 * @return string * */ public String doGet(String url) { return doGet(url, null, null); } /** * get 请求 * @param url 请求url地址 * @param params 请求参数 map * @return string * */ public String doGet(String url, Map<String, String> params) { return doGet(url, params, null); } /** * get 请求 * @param url 请求url地址 * @param headers 请求头字段 {k1, v1 k2, v2, ...} * @return string * */ public String doGet(String url, String[] headers) { return doGet(url, null, headers); } /** * get 请求 * @param url 请求url地址 * @param params 请求参数 map * @param headers 请求头字段 {k1, v1 k2, v2, ...} * @return string * */ public String doGet(String url, Map<String, String> params, String[] headers) { StringBuilder sb = new StringBuilder(url); if (params != null && params.keySet().size() > 0) { boolean firstFlag = true; for (String key : params.keySet()) { if (firstFlag) { sb.append("?").append(key).append("=").append(params.get(key)); firstFlag = false; } else { sb.append("&").append(key).append("=").append(params.get(key)); } } } Request.Builder builder = new Request.Builder(); if (headers != null && headers.length > 0) { if (headers.length % 2 == 0) { for (int i = 0; i < headers.length; i = i + 2) { builder.addHeader(headers[i], headers[i + 1]); } } else { log.warn("headers's length[{}] is error.", headers.length); } } Request request = builder.url(sb.toString()).build(); log.info("do get request and url[{}]", sb.toString()); return execute(request); } /** * post 请求 * @param url 请求url地址 * @param params 请求参数 map * @return string */ public String doPost(String url, Map<String, String> params) { FormBody.Builder builder = new FormBody.Builder(); if (params != null && params.keySet().size() > 0) { for (String key : params.keySet()) { builder.add(key, params.get(key)); } } Request request = new Request.Builder().url(url).post(builder.build()).build(); log.info("do post request and url[{}]", url); return execute(request); } /** * post 请求, 请求数据为 json 的字符串 * @param url 请求url地址 * @param json 请求数据, json 字符串 * @return string */ public String doPostJson(String url, String json) { log.info("do post request and url[{}]", url); return exectePost(url, json, JSON); } /** * post 请求, 请求数据为 xml 的字符串 * @param url 请求url地址 * @param xml 请求数据, xml 字符串 * @return string */ public String doPostXml(String url, String xml) { log.info("do post request and url[{}]", url); return exectePost(url, xml, XML); } private String exectePost(String url, String data, MediaType contentType) { RequestBody requestBody = RequestBody.create(contentType, data); Request request = new Request.Builder().url(url).post(requestBody).build(); return execute(request); } private String execute(Request request) { Response response = null; try { response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } } catch (Exception e) { log.error(ExceptionUtils.getStackTrace(e)); } finally { if (response != null) { response.close(); } } return ""; } }
看完打开支付宝扫一扫领个红包吧!