Java下載https檔案並上傳阿里雲oss伺服器
阿新 • • 發佈:2020-01-18
這篇文章主要介紹了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返回上傳之後路徑。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。