- 2017-4-25更新:
- 今天用OSS上传文件又遇到了问题
- 问题描述:unknown host:jalon-test.oss-cn-beijing.aliyuncs.com/;以前都是好好的,今天却出错了;
- 原因:在官网检查了好久,原来是https的缘故;因为oss在北京区域的请求头从http更新到了https,导致访问主机一直错误;
- 解决办法:将OSSClient的endpoint配置从http://oss-cn-beijing.aliyuncs.com改成https://oss-cn-beijing.aliyuncs.com
之前的问题:
摘自:阿里云官网 https://help.aliyun.com/document_detail/32024.html
当时出现了如下的错误:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/ssl/TrustStrategy
at com.aliyun.oss.OSSClient.<init>(OSSClient.java:268)
at com.aliyun.oss.OSSClient.<init>(OSSClient.java:193)
at com.aliyun.oss.demo.HelloOSS.main(HelloOSS.java:77)
Caused by: java.lang.ClassNotFoundException: org.apache.http.ssl.TrustStrategy
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 3 more
原因是包依赖出现了问题,阿里云的oss SDK引用了apache httpclient 4.4.1,而我项目里也引入了,但是版本不同,所以才会出问题。可以在工程目录下运行“mvn dependency:tree”,就可以看到相互之间的依赖
下面是解决包依赖的两种方法:
- 使用统一版本。如果您的工程里使用与Apache httpclient
4.4.1冲突的版本,请您也使用4.4.1版本。在pom.xml去掉其它版本的Apache httpclient依赖。如果您的工程使用了commons-httpclient也可能存在冲突,请去除commons-httpclient。 - 解除依赖冲突。如果您的工程依赖与多个第三方包,而第三方包又依赖不同版本的Apache
httpclient,您的工程里会有依赖冲突,请使用exclusion解除。详细请参考maven guides。
我的项目中用到了httpclient4.3.6,代码如下所示,只能用第一种方法,将版本提高为4.4.1;如果用第二种,将阿里云SDK中依赖的httpclient去掉,那么还是会有错,因为我项目中的httpclient版本低
<!-- Apache Http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.6</version>
</dependency>
<!-- Apache Http client END-->
下面是测试代码:
public static void main(String[] args)
{
// endpoint以北京为例,其它region请按实际情况填写
String endpoint = "http://oss-cn-beijing.aliyuncs.com";
// accessKey请登录https://ak-console.aliyun.com/#/查看
String accessKeyId = "*****************";
String accessKeySecret = "********************";
// 创建OSSClient实例
OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//获取项目的根路径:user.dir意思就是获取项目的根路径,不是说获取user.dir这个目录;但是到了Linux服务器上,获取到的是/java/apache-tomcat-8.0.24/bin/,不知道为啥
String dir = System.getProperty("user.dir");
System.out.println(dir);
//上传文件
client.putObject("jalon-test", "1.jpg", new File("E:\\1.jpg"));
//下载文件
client.getObject(new GetObjectRequest("jalon-test","1.jpg"),new File(dir+"\\1.jpg"));
}
下面是运行结果:E:\SVN_WorkSpace\shoes_src,然后1.jpg已经成功上传到oss,且下载到项目根目录下