java实现创蓝短信

前段时间因为节约成本,公司改用创蓝短信,以此记录一下自己从0到最后写完这个接口(不喜勿喷),有任何问题欢迎私信小弟'

  1. 第一步习惯性观看官网api,官网地址是https://www.253.com,找到api文档下的demo下载如图java实现创蓝短信_第1张图片
  2.  这里我是java,就选择java下载,下载完成后是放到idea里java实现创蓝短信_第2张图片

接下来测试这个demo,注意看我图片的的注释

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.dql.lms.chuanglan.request.SmsSendRequest;
import com.dql.lms.chuanglan.response.SmsSendResponse;

/**
 * 
 * @author tianyh 
 * @Description:HTTP 请求
 */
public class ChuangLanSmsUtil {
	protected static final Logger logger = LoggerFactory.getLogger(ChuangLanSmsUtil.class);
	
	public static final String MOBILENUMBER = "4000986661";
	
	public static final String ACCOUNT = "公司的api接口账号";
	
	public static final String PSWD = "公司的api接口密码";
	//请求地址
	public static final String URL = "http://smssh1.253.com/msg/send/json";
	/**
	 * 
	 * @author tianyh 
	 * @Description 
	 * @param path
	 * @param postContent
	 * @return String 
	 * @throws
	 */测试代码,手机号测试
           
	@Test
	public static void main(String[] args) {
                    //手机号和短信模板
		sendMessage("phone","msg");

	}



	public static String sendSmsByPost(String postContent) {
		URL url = null;
		try {
			url = new URL(ChuangLanSmsUtil.URL);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setRequestMethod("POST");// 提交模式
			httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
			httpURLConnection.setReadTimeout(2000);//读取超时 单位毫秒
			// 发送POST请求必须设置如下两行
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			httpURLConnection.setRequestProperty("Content-Type", "application/json");
			
//			PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
//			printWriter.write(postContent);
//			printWriter.flush();

			httpURLConnection.connect();
			OutputStream os=httpURLConnection.getOutputStream();
			os.write(postContent.getBytes("UTF-8"));
			os.flush();
			
			StringBuilder sb = new StringBuilder();
			int httpRspCode = httpURLConnection.getResponseCode();
			if (httpRspCode == HttpURLConnection.HTTP_OK) {
				// 开始获取数据
				BufferedReader br = new BufferedReader(
						new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
				String line = null;
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
				br.close();
				return sb.toString();

			}

		} catch (Exception e) {
			logger.warn("Ignore this exception"+e);
		}
		return null;
	}

	public static String sendMessage(String phone, String content){
		String returnStr = "";
		//状态报告
		String report= "true";
		
		SmsSendRequest smsSingleRequest = new SmsSendRequest(ChuangLanSmsUtil.ACCOUNT, ChuangLanSmsUtil.PSWD, content, phone,report);
		
		String requestJson = JSON.toJSONString(smsSingleRequest);
		
		logger.info("======requestString======= " + requestJson);
		
		String response = ChuangLanSmsUtil.sendSmsByPost(requestJson);
		if(response != null && !response.equals("")){
			logger.info("======responseString======" + response);
			SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);
			returnStr = smsSingleResponse.getErrorMsg();
		}
		return returnStr;
    }

}

4.测试没有问题继续编写接口,马上代码部分

/**
	 * 注册发送验证码
	 * 
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "sendCode")
	@ResponseBody
	public Map sendCode(HttpServletRequest request, HttpSession session) throws Exception {

		//String str1= ChuangLanSmsUtil.sendMessage( "手机号",SEND_MSG + "123456");
		Map map = new HashMap<>();
		String phone = request.getParameter("phone");
		String key = "reg_code_"+phone;
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9])|(17[0-9]))\\d{8}$");
		if (p.matcher(phone).matches() == false) {
			map.put("msg", "手机格式不正确");
			map.put("success", false);
			return map;
		}
		if (phone == null || "".equals(phone)) {
			map.put("msg", "手机号不能为空");
			map.put("success", false);
		} else {
//			User user = userService.findByPhone(phone);
//			if (user != null) {
//				map.put("msg", "手机号已被注册");
//				map.put("success", false);
//			} else {
				String mobileCode = NumberUtil.getFixLenthString(6);

				Map codeMap = new HashMap();
				codeMap.put(phone, mobileCode);
				session.setAttribute("regist" + phone, codeMap);
				// 添加短信发送代码()
				/*String str = SendSmsUtil.sendSMS("213409", phone, new String[]{mobileCode});*/
			     //String str1= ChuangLanSmsUtil.sendMessage( phone,SEND_MSG + mobileCode);
			     String str= ChuangLanSmsUtil.sendMessage( phone,SEND_MSG + mobileCode);
				if(str.equals("")){
					map.put("msg", "发送短信成功!");
					map.put("status", "1");
					map.put("success", true);
				}else{
					map.put("msg", str);
					map.put("status", "0");
					map.put("success", false);
				}
//			}
		}
		return map;
	}

5,直接测试注意前面得定义 send_msg

public static final String SEND_MSG = "【xx】您的验证码是:";

你可能感兴趣的:(后端)