发表于: 2020-07-11 23:05:20
1 1286
今天完成的事情:
之前用的那个容联云短信只能使用自己的手机测试,今天花了好久换成阿里云的短信接口了:
导入依赖:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.3</version>
</dependency>
写了一个发短信工具类:
package com.jnshu.util;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.whalin.MemCached.MemCachedClient;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
//阿里云短信
public class AlSDKTest {
@Autowired
MemCachedClient memCachedClient;
private String regionId;
private String accessKeyId;
private String secret;
private String Rand_Code = RandNum.getRandLength(4);
private static Logger logger = Logger.getLogger(AlSDKTest.class);
public String getRegionId() {
return regionId;
}
public void setRegionId(String regionId) {
this.regionId = regionId;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public AlSDKTest(String regionId, String accessKeyId, String secret) {
this.regionId = regionId;
this.accessKeyId = accessKeyId;
this.secret = secret;
}
public boolean getSms(String phone) {
logger.info("code:"+Rand_Code);
DefaultProfile profile = DefaultProfile.getProfile(regionId,accessKeyId,secret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain("dysmsapi.aliyuncs.com");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", phone);
request.putQueryParameter("SignName", "任务七注册");
request.putQueryParameter("TemplateCode", "SMS_195872171");
request.putQueryParameter("TemplateParam", String.format("{\"code\":\"%s\"}", Rand_Code));
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
memCachedClient.set("code"+ phone,Rand_Code,new Date(1000*60));
logger.info("存入Memcached的code:"+ Rand_Code);
return true;
} catch (ServerException e) {
e.printStackTrace();
return false;
} catch (ClientException e) {
e.printStackTrace();
return false;
}
}
}
在spring中注入:
<!--注入阿里云短信接口-->
<bean id="aliyun" class="com.jnshu.util.AlSDKTest">
<constructor-arg name="regionId" value="cn-hangzhou"/>
<constructor-arg name="accessKeyId" value="LTAI4GCiq9fnW2YJLqruCZkd"/>
<constructor-arg name="secret" value="kydiM0erIY5HwRxtLOBqg9Y0bxlFuL"/>
</bean>
测试成功:
接下来完成上传图片的:
这里我为了方便还是用的阿里云的
在官网注册之后可以免费用一个月,在控制台上传个图片试试:
通过url访问:
接下来整合到项目里:
首先还是导入依赖:
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
写了个测试类把官网的接口拿过来简单测试了一下,大概会用了:
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import org.junit.Test;
import java.io.*;
public class AliyunImage {
// Endpoint以杭州为例,其它Region请按实际情况填写。
private String endpoint = "oss-cn-beijing.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
private String accessKeyId = "LTAI4GCiq9fnW2YJLqruCZkd";
private String accessKeySecret = "kydiM0erIY5HwRxtLOBqg9Y0bxlFuL";
private String bucketName = "zhanghaotask7";
@Test
public void upload() throws FileNotFoundException {
// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
String file = "${pageContext.request.contextPath}/imges/背景.jpg";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
InputStream inputStream = new FileInputStream("C:\\Users\\zhanghao\\IdeaProjects\\task\\task7\\src\\main\\webapp\\imges\\背景.jpg");
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType("image/jpg");
// 上传文件到指定的存储空间(bucketName)并将其保存为指定的文件名称(objectName)。
ossClient.putObject(bucketName,"a",inputStream,objectMetadata);
// 关闭OSSClient。
ossClient.shutdown();
}
@Test
public void delete() {
// <yourObjectName>表示删除OSS文件时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
String objectName = "${pageContext.request.contextPath}/imges/背景.jpg";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 删除文件。
ossClient.deleteObject(bucketName, objectName);
// 关闭OSSClient。
ossClient.shutdown();
}
@Test
public void download() throws IOException {
// <yourObjectName>从OSS下载文件时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
String objectName = "preview.jpg";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 调用ossClient.getObject返回一个OSSObject实例,该实例包含文件内容及文件元信息。
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
// 调用ossObject.getObjectContent获取文件输入流,可读取此输入流获取其内容。
InputStream content = ossObject.getObjectContent();
if (content != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
while (true) {
String line = reader.readLine();
if (line == null) break;
System.out.println("\n" + line);
}
// 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
content.close();
}
// 关闭OSSClient。
ossClient.shutdown();
}
@Test
public void select(){
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// ossClient.listObjects返回ObjectListing实例,包含此次listObject请求的返回结果。
ObjectListing objectListing = ossClient.listObjects(bucketName);
// objectListing.getObjectSummaries获取所有文件的描述信息。
for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
System.out.println(" - " + objectSummary.getKey() + " " +
"(size = " + objectSummary.getSize() + ")");
}
// 关闭OSSClient。
ossClient.shutdown();
}
}
写一个工具类:
package com.jnshu.util;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import java.io.*;
public class ImageUtil {
// Endpoint以杭州为例,其它Region请按实际情况填写。
private String endpoint;
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
private String key = "images/";
public ImageUtil(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
this.endpoint = endpoint;
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
this.bucketName = bucketName;
}
public String upload(String file) throws FileNotFoundException {
//获取文件名
file.trim();
String fileName = file.substring(file.lastIndexOf("/")+1);
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//上传文件流
InputStream inputStream = new FileInputStream(file);
//设置上传文件格式
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType("image/jpg");
ossClient.putObject(bucketName,key + fileName,inputStream,objectMetadata);
//图片url
String url = bucketName + "." + endpoint + "/" + key + fileName;
// 关闭OSSClient。
ossClient.shutdown();
return url;}
}
上传图片返回图片链接,运行结果:
有点问题是传入的文件路径中识别不了中文和“-”之类的符号。
收获:
初步学会使用阿里云OOS上传图片
明天计划完成的事情:
完善代码,整合进项目里。
评论