使用七牛云仓库下载文件:
下载的文件要把pom中的OKHTTP换成3.6.0版本
<!--OKHTTP-->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
package com.example.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.util.Auth;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class DownLoad {
// 设置需要操作的账号的AK和SK (AK和SK均在七牛云中获得,以下会说明)
private static final String ACCESS_KEY = "ACCESS_KEY ";
private static final String SECRET_KEY = "SECRET_KEY ";
// 要上传的空间 (刚刚新建空间的名称)
private static final String bucketname = "imgstest";
// 密钥
private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
//地区分布实例化
private static final Configuration cfg = new Configuration(Region.huanan());
//新建空间时,七牛云分配出的域名 (自己可在万网购买域名解析后,绑定到加速域名)
private static final String DOMAIN = "rilbajsto.hn-bkt.clouddn.com";
/**
* 获取下载文件路径,即:donwloadUrl
*/
public String getDownloadUrl(String targetUrl) {
String downloadUrl = auth.privateDownloadUrl(targetUrl);
return downloadUrl;
}
/**
* 下载
*/
public void download(String targetUrl) {
//获取downloadUrl
String downloadUrl = getDownloadUrl(targetUrl);
//本地保存路径
String filePath = "E:\\imgs";
download(downloadUrl, filePath);
}
/**
* 通过发送http get 请求获取文件资源
*/
private static void download(String url, String filepath) {
OkHttpClient client = new OkHttpClient();
System.out.println(url);
Request req = new Request.Builder().url(url).build();
Response resp = null;
try {
resp = client.newCall(req).execute();
System.out.println(resp.isSuccessful());
if(resp.isSuccessful()) {
ResponseBody body = resp.body();
InputStream is = body.byteStream();
byte[] data = readInputStream(is);
File imgFile = new File(filepath + "\\download.jpeg"); //下载到本地的图片命名
FileOutputStream fops = new FileOutputStream(imgFile);
fops.write(data);
fops.close();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Unexpected code " + resp);
}
}
/**
* 读取字节输入流内容
*/
private static byte[] readInputStream(InputStream is) {
ByteArrayOutputStream writer = new ByteArrayOutputStream();
byte[] buff = new byte[1024 * 2];
int len = 0;
try {
while((len = is.read(buff)) != -1) {
writer.write(buff, 0, len);
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return writer.toByteArray();
}
/**
* 主函数:测试
*/
public static void main(String[] args) {
//构造私有空间的需要生成的下载的链接;
//格式: http://私有空间绑定的域名/空间下的文件名
String targetUrl = "http://rilbajsto.hn-bkt.clouddn.com/FlFEDbuL_QygvPXF-lWg5NxxgunD"; //外链域名下的图片路径
new DownLoad().download(targetUrl);
}
}