七牛クラウドストレージのダウンロードプライベートスペースファイル
6040 ワード
package com.qiniu.kodo;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.qiniu.base.AccountMgr;
import com.qiniu.util.Auth;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
*
* @author xuhuanchao
*
*/
public class Download {
//
Auth auth = Auth.create(AccountMgr.ACCESS_KEY, AccountMgr.SECRET_KEY);
/**
* , :donwloadUrl
* @return
*/
public String getDownloadUrl(String targetUrl) {
String downloadUrl = auth.privateDownloadUrl(targetUrl);
return downloadUrl;
}
/**
*
*/
public void download(String targetUrl) {
// downloadUrl
String downloadUrl = getDownloadUrl(targetUrl);
//
String filePath = "/Users/xuhuanchao/Documents/admin/download/";
download(downloadUrl, filePath);
}
/**
* http get
* @param url
* @param filepath
* @return
*/
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 + "admin_2.png");
FileOutputStream fops = new FileOutputStream(imgFile);
fops.write(data);
fops.close();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Unexpected code " + resp);
}
}
/**
*
* @param is
* @return
*/
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();
}
/**
* :
* @param args
*/
public static void main(String[] args) {
// ;
// : http:// /
String targetUrl = "http://oddbqeh34.bkt.clouddn.com/admin_2.png";
new Download().download(targetUrl);
}
}
注意:qiniu-java-sdk-7.2.1が現在使用されています.jar