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 = "http://oss-devimage.xxxx.com/"; bucketServer = "http://dev-uploadtoimages.oss-cn-beijing.aliyuncs.com/"; // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。 String accessKeyId = ossJson.getString("accessKeyId"); String accessKeySecret = ossJson.getString("accessKeySecret"); String security = ossJson.getString("security"); // 创建OSSClient实例。 OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, security); // 上传网络流。 SSLContext sslcontext = SSLContext.getInstance("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.setDefaultSSLSocketFactory(sslcontext.getSocketFactory()); HttpsURLConnection urlCon = (HttpsURLConnection) url.openConnection(); urlCon.setConnectTimeout(6000); urlCon.setReadTimeout(6000); int code = urlCon.getResponseCode(); if (code != HttpURLConnection.HTTP_OK) { throw new Exception("文件读取失败"); } // 读文件流 InputStream inputStream = urlCon.getInputStream(); // 上传文件 (上传文件流的形式) 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返回上传之后路径。