Java下载https⽂件并上传阿⾥云oss服务器
这篇⽂章主要介绍了Java下载https⽂件并上传到阿⾥云oss服务器,⽂中通过⽰例代码介绍的⾮常详细,对⼤家的学习或者⼯作具有⼀定的参考学习价值,需要的朋友可以参考下
今天做了⼀个从Https链接中下载⾳频并且上传到OSS服务器,记录⼀下希望⼤家也少⾛弯路。
⼀共两个类:
1 、实现⾃⼰的证书信任管理器类
/**
* @author mazhq
* @Title: X509TrustUtiil
* @ProjectName: zeus
* @Description: 证书信任管理器类
* @date 2019/2/18 15:14
*/
public class X509TrustUtil implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
2、阿⾥云上传⼯具类
/**
* @author mazhq
* @Title: OSSUtil
* @ProjectName: zeus
* @Description: TODO
* @date 2019/2/18 14:07
*/
public class OSSUtil {
/**
* @Description: 上传⽂件到阿⾥云
* @param recordingLink
* @param fileName
* @return void
* @exception
* @author mazhq
* @date 2019/2/18 14:30
*/
public static String uploadRecording(JSONObject ossJson, String recordingLink, String fileName){
try {
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "";
String bucketServer;
String bucketName;
bucketName = "dev-uploadtoimages";
endpoint = "/";
connect下载
bucketServer = "dev-uploadtoimages.oss-cn-beijing.aliyuncs/";
// 阿⾥云主账号AccessKey拥有所有API的访问权限,风险很⾼。强烈建议您创建并使⽤RAM账号进⾏API访问或⽇常运维,请登录 sole.aliyun 创建RAM账号。      String accessKeyId = String("accessKeyId");
String accessKeySecret = String("accessKeySecret");
String security = String("security");
// 创建OSSClient实例。
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, security);
// 上传⽹络流。
SSLContext sslcontext = Instance("SSL", "SunJSSE");
sslcontext.init(null, new TrustManager[] { new X509TrustUtil() }, new java.security.SecureRandom());
URL url = new URL(recordingLink);
HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
public boolean verify(String s, SSLSession sslsession) {
System.out.println("WARNING: Hostname is not matched for cert.");
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
HttpsURLConnection.SocketFactory());
HttpsURLConnection urlCon = (HttpsURLConnection) url.openConnection();
urlCon.setConnectTimeout(6000);
urlCon.setReadTimeout(6000);
int code = ResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new Exception("⽂件读取失败");
}
/
/ 读⽂件流
InputStream inputStream = InputStream();
// 上传⽂件 (上传⽂件流的形式)
ossClient.putObject(bucketName, "recording/"+fileName, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
return bucketServer+"recording/"+fileName;
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
结论:
两个类搭配着⽤,完美解决下载https⽂件上传到阿⾥oss返回上传之后路径。
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。