今天作了一個從Https連接中下載音頻而且上傳到OSS服務器,記錄一下但願你們也少走彎路。java
一共兩個類:vim
/** * @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]; } }
/** * @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返回上傳以後路徑。網絡