栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

短信、邮箱、http请求工具

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

短信、邮箱、http请求工具

一、短信 1、容联云短信 (1)官网:https://www.yuntongxun.com/member/main (2)登录注册,进入控制台首页

(3)开发文档

https://doc.yuntongxun.com/p/5f0299f4a80948a1006e775e

(4)导入依赖

    com.cloopen
    java-sms-sdk
    1.0.3

(5)调用示例测试
//生产环境请求地址:app.cloopen.com
    String serverIp = "app.cloopen.com";
    //请求端口
    String serverPort = "8883";
    //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
    String accountSId = "你的accountSId";
    String accountToken = "你的auth token";
    //请使用管理控制台中已创建应用的APPID
    String appId = "你的appId";
    CCPRestSmsSDK sdk = new CCPRestSmsSDK();
    sdk.init(serverIp, serverPort);
    sdk.setAccount(accountSId, accountToken);
    sdk.setAppId(appId);
    sdk.setBodyType(BodyType.Type_JSON);
    String to = "1352*******";
    String templateId= "templateId";
    String[] datas = {"变量1","变量2","变量3"};
    //String subAppend="1234";  //可选 扩展码,四位数字 0~9999
    //String reqId="fadfafas";  //可选 第三方自定义消息id,最大支持32位英文数字,同账号下同一自然天内不允许重复
    HashMap result = sdk.sendTemplateSMS(to,templateId,datas);
    //HashMap result = sdk.sendTemplateSMS(to,templateId,datas,subAppend,reqId);
    if("000000".equals(result.get("statusCode"))){
        //正常返回输出data包体信息(map)
        HashMap data = (HashMap) result.get("data");
        Set keySet = data.keySet();
        for(String key:keySet){
            Object object = data.get(key);
            System.out.println(key +" = "+object);
        }
    }else{
        //异常返回输出错误码和错误信息
        System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
    }
(6)正式调用环境

application.yml

spring:
  sms:
    #生产环境请求地址:app.cloopen.com
    serverIp: app.cloopen.com
    #请求端口
    serverPort: 8883
    #开发者主账号ACCOUNT SID
    accountSId: 你的accountSId
    #主账号令牌AUTH TOKEN
    accountToken: 你的AUTH TOKEN
    #请使用管理控制台中已创建应用的APPID
    appId: 你的AppID

SmsTools

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Set;

@Data
@ConfigurationProperties(prefix = "spring.sms")
@Component
public class SmsTools {

    //生产环境请求地址:app.cloopen.com
    private String serverIp;
    //请求端口
    private String serverPort;
    //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
    private String accountSId;
    private String accountToken;
    //请使用管理控制台中已创建应用的APPID
    private String appId;

    
    public Boolean sendSms(String to,String templateId,String[] datas){

        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);

        HashMap result = sdk.sendTemplateSMS(to,templateId,datas);
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息(map)
            HashMap data = (HashMap) result.get("data");
            Set keySet = data.keySet();
            for(String key:keySet){
                Object object = data.get(key);
                System.out.println(key +" = "+object);
            }
            return true;
        }else{
            //异常返回输出错误码和错误信息
            System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
            return false;
        }
    }
}

调用测试

	@Resource
	private SmsTools smsTools;

	@Test
    void sendSms(){
        Boolean sendSms = smsTools.sendSms("18886330640", "1", new String[]{"2345", "5"});
        System.out.println(sendSms);
    }

随机生成4位数验证码代码

	public static int getRandomCode(){		
		int max=9999;
        int min=1111;
        Random random = new Random();
        return random.nextInt(max)%(max-min+1) + min;		
	}

2、阿里云

参考这个链接:https://www.yuque.com/zhangshuaiyin/guli-mall/ktswm9

二、邮箱

QQ邮箱接入手册
https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=371

1、引入依赖
	   
        
            org.springframework.boot
            spring-boot-starter-mail
        
        
        
            org.springframework.boot
            spring-boot-starter-freemarker
        
2、MailTools
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Map;


@Component
@ConfigurationProperties(prefix = "spring.mail")
@Data
public class MailTools {
    @Resource
    private JavaMailSenderImpl mailSender;
    @Resource
    private FreeMarkerConfigurer freeMarkerConfigurer;
    private String subject;
    private String from;


    
    public void sendSimpleEmail(String mailContent,String...to){
        this.sendSimpleEmail(subject,mailContent,to);
    }
    
    public void sendSimpleEmail(String subject,String mailContent,String...to){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject(subject);//设置邮件主题
        mailMessage.setTo(to);//设置发送给谁
        mailMessage.setFrom(from);//设置谁发送的邮件
        mailMessage.setText(mailContent);//设置邮件内容
        mailSender.send(mailMessage);
    }

    
    public void sendMimeMail(String subject,String mailContent,String...to) throws MessagingException {
        this.sendMimeMail(subject,mailContent,null,to);
    }

    
    public void sendMimeMail(String mailContent,String...to) throws MessagingException {
        this.sendMimeMail(this.subject,mailContent,null,to);
    }

    
    public void sendMimeMail(String subject, String mailContent, File[] files, String...to) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);//这个true表示发送带附件的邮件
        helper.setFrom(from);
        helper.setTo(to);
        //设置主题
        helper.setSubject(subject);
        helper.setText(mailContent,true);//表示html类型的邮件
        //设置附件
        if(files!=null && files.length>0){
            for (File file:files){
                if(file!=null){
                    String filename = file.getName();//获取上传文件名称
                    helper.addAttachment(filename,file);
                }
            }
        }
        mailSender.send(mimeMessage);
    }

    
    public void sendTemplateMail(String subject, Map model, String templatePath, String...to) throws IOException, TemplateException, MessagingException {
        // 获得模板
        Template mailTemplate = freeMarkerConfigurer.getConfiguration().getTemplate(templatePath);
        // 传入数据模型到模板,替代模板中的占位符,并将模板转化为html字符串
        String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(mailTemplate,model);
        // 该方法本质上还是发送html邮件,调用之前发送html邮件的方法
        this.sendMimeMail(subject,templateHtml,to);
    }

}

3、application.yml
spring:
  #QQ邮箱
  mail:
    protocol: smtp              
    host: smtp.qq.com           
    port: 587                   
    username: 40594@qq.com   #你的QQ账号
    password: 你的密码  #获取密码
    from: 40594@qq.com  #发送账号

  freemarker:
    template-loader-path: classpath:/templates/mail/  
    suffix: .ftl                                      
    cache: false                                      
    charset: UTF-8                                    
4、邮件模板account_active.ftl



    
    
    


尊敬的${name},您好!

欢迎成为XXX家族成员的一份子,您此次账户注册的激活码为:${code},该激活码用于注册用户激活账户使用,请妥善保管! 请于30分钟内输入激活!

5、测试调用
	@Resource
    private MailTools mailTools;

    @Test
    void sendMail() throws TemplateException, IOException, MessagingException {
        String templateName = "account_active.ftl";//模板名称
        //用于设置你要替换模板中的哪个一个占位符,以及值
        Map model = new HashMap<>();
        //把日期格式转化成字符串
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String datetime = sdf.format(date);
        model.put("name","昵称");
        model.put("code","6270");
        model.put("datetime",datetime);
        mailTools.sendTemplateMail("邮箱注册主题",model,templateName,"9605940@qq.com");
    }
6、pom.xml
    
    	
            
                ${basedir}/src/main/java
                
                    ***.java
                
                false
            
        
    
三、第三方请求方式工具HttpUtils

HttpUtils.java地址:https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java

pom.xml地址:https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml

		
			com.alibaba
			fastjson
			1.2.15
		
        
            org.apache.httpcomponents
            httpclient
            4.2.1
        
        
            org.apache.httpcomponents
            httpcore
            4.2.1
        
        
            commons-lang
            commons-lang
            2.6
        
        
            org.eclipse.jetty
            jetty-util
            9.3.7.v20160115
        
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NamevaluePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNamevaluePair;

public class HttpUtils {
	
	
	public static HttpResponse doGet(String host, String path, String method, 
			Map headers, 
			Map querys)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }
        
        return httpClient.execute(request);
    }
	
	
	public static HttpResponse doPost(String host, String path, String method, 
			Map headers, 
			Map querys, 
			Map bodys)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List namevaluePairList = new ArrayList();

            for (String key : bodys.keySet()) {
                namevaluePairList.add(new BasicNamevaluePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(namevaluePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }	
	
	
	public static HttpResponse doPost(String host, String path, String method, 
			Map headers, 
			Map querys, 
			String body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
        	request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }
	
	
	public static HttpResponse doPost(String host, String path, String method, 
			Map headers, 
			Map querys, 
			byte[] body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
        	request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }
	
	
	public static HttpResponse doPut(String host, String path, String method, 
			Map headers, 
			Map querys, 
			String body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
        	request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }
	
	
	public static HttpResponse doPut(String host, String path, String method, 
			Map headers, 
			Map querys, 
			byte[] body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
        	request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }
	
	
	public static HttpResponse doDelete(String host, String path, String method, 
			Map headers, 
			Map querys)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }
        
        return httpClient.execute(request);
    }
	
	private static String buildUrl(String host, String path, Map querys) throws UnsupportedEncodingException {
    	StringBuilder sbUrl = new StringBuilder();
    	sbUrl.append(host);
    	if (!StringUtils.isBlank(path)) {
    		sbUrl.append(path);
        }
    	if (null != querys) {
    		StringBuilder sbQuery = new StringBuilder();
        	for (Map.Entry query : querys.entrySet()) {
        		if (0 < sbQuery.length()) {
        			sbQuery.append("&");
        		}
        		if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
        			sbQuery.append(query.getValue());
                }
        		if (!StringUtils.isBlank(query.getKey())) {
        			sbQuery.append(query.getKey());
        			if (!StringUtils.isBlank(query.getValue())) {
        				sbQuery.append("=");
        				sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
        			}        			
                }
        	}
        	if (0 < sbQuery.length()) {
        		sbUrl.append("?").append(sbQuery);
        	}
        }
    	
    	return sbUrl.toString();
    }
	
	private static HttpClient wrapClient(String host) {
		HttpClient httpClient = new DefaultHttpClient();
		if (host.startsWith("https://")) {
			sslClient(httpClient);
		}
		
		return httpClient;
	}
	
	private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                	
                }
                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                	
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
        	throw new RuntimeException(ex);
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/748966.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号