公司开发用到了很多阿里云的产品,几乎第三方SDK,云服务器什么的老板都用阿里云的。
一:发短信功能
引入pom依赖
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.1.0</version>
</dependency>
这个直接写了一个工具类
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
public class SendPhoneCode {
public void sendCode(String telephone,String randomValidateCode,String smsParameters) throws ServerException, ClientException {
final String product = "Dysmsapi";
final String domain = "dysmsapi.aliyuncs.com";
final String accessKeyId = "阿里云accessKeyId";
final String accessKeySecret = "阿里云accessKeySecret";
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request.setMethod(MethodType.POST);
request.setPhoneNumbers(telephone);//手机号
request.setSignName("XX网络");//短信名
request.setTemplateCode(smsParameters);
request.setTemplateParam("{\"code\":" + randomValidateCode + "}");
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
System.out.println("发送成功~");
} else {
System.out.println("发送失败~");
}
}
}
然后根据业务需要在需要发送短信验证码的地方直接调用这个工具类即可。
二:上传图片到阿里云OSS
引入pom依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.2</version>
</dependency>
封装上传图片工具类
import java.io.File;
import java.util.Date;
import com.aliyun.oss.OSSClient;
public class UploadSample {
public static String uploadImage(String packageName,File file,String name){
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "oss-cn-beijing.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
String accessKeyId = "阿里云accessKeyId";
String accessKeySecret = "阿里云accessKeySecret";
// 创建OSSClient实例。
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
// 上传文件。
ossClient