这篇文章主要介绍了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 ; 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返回上传之后路径。