导入依赖

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.13</version>
</dependency>

配置

用户名和秘钥都需要自己获取,注册短信平台

application.properties

# 短信验证的用户名
message.uid=xxxxx
# 短信验证的秘钥
message.key=xxxxxx

工具类HttpClientUtil

package com.it.whitejotterapi.tools;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author: 羡羡
* @Date: 2022/05/29/11:00
*/
public class HttpClientUtil {
private RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(15000)
.setConnectTimeout(15000)
.setConnectionRequestTimeout(15000)
.build();
private static HttpClientUtil instance = null;
private HttpClientUtil(){}
public static HttpClientUtil getInstance(){
if (instance == null) {
instance = new HttpClientUtil();
}
return instance;
}
/**
* 发送 post请求
* @param httpUrl 地址
*/
public String sendHttpPost(String httpUrl) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
return sendHttpPost(httpPost,"utf-8");
}

/**
* 发送 post请求
* @param httpUrl 地址
* @param maps 参数
* @param type 字符编码格式
*/
public String sendHttpPost(String httpUrl, Map<String, String> maps,String type) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
// 创建参数队列
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (String key : maps.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, type));
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost,type);
}
/**
* 发送Post请求
* @param httpPost
* @return
*/
private String sendHttpPost(HttpPost httpPost,String reponseType) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = HttpClients.createDefault();
httpPost.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpPost);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, reponseType);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送 get请求
* @param httpUrl
*/
public String sendHttpGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
return sendHttpGet(httpGet);
}
/**
* 发送 get请求Https
* @param httpUrl
*/
public String sendHttpsGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
return sendHttpsGet(httpGet);
}
/**
* @Title: sendMsgUtf8
* @Description: TODO(发送utf8)
* @param: @param Uid
* @param: @param Key
* @param: @param content
* @param: @param mobiles
* @param: @return
* @date: 2017-3-22 下午5:58:07
* @throws
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public int sendMsgUtf8(String Uid,String Key,String content,String mobiles){
Map maps = new HashMap();
maps.put("Uid", Uid);
maps.put("Key", Key);
maps.put("smsMob", mobiles);
maps.put("smsText", content);
String result = sendHttpPost("http://utf8.sms.webchinese.cn", maps, "utf-8");
return Integer.parseInt(result);
}
/**
* @Title: sendMsgUtf8
* @Description: TODO(发送utf8)
* @param: @param Uid
* @param: @param Key
* @param: @param content
* @param: @param mobiles
* @param: @return
* @return: int
* @author: ly
* @date: 2017-3-22 下午5:58:07
* @throws
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public int sendMsgGbk(String Uid,String Key,String content,String mobiles){
Map maps = new HashMap();
maps.put("Uid", Uid);
maps.put("Key", Key);
maps.put("smsMob", mobiles);
maps.put("smsText", content);
String result = sendHttpPost("http://gbk.sms.webchinese.cn", maps, "gbk");
return Integer.parseInt(result);
}
/**
* 发送Get请求
* @param httpGet
* @return
*/
private String sendHttpGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = HttpClients.createDefault();
httpGet.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送Get请求Https
* @param httpGet
* @return
*/
private String sendHttpsGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
httpGet.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* @Title: getErrorMsg
* @Description: TODO(返回异常原因)
* @param: @param errorCode
*/
public String getErrorMsg(int errorCode){
if(errorCode==-1){
return "没有该用户账户";
}else if(errorCode==-2){
return "接口密钥不正确";
}else if(errorCode==-3){
return "短信数量不足";
}else if(errorCode==-4){
return "手机号格式不正确";
}else if(errorCode==-21){
return "MD5接口密钥加密不正确";
}else if(errorCode==-11){
return "该用户被禁用";
}else if(errorCode==-14){
return "短信内容出现非法字符";
}else if(errorCode==-41){
return "手机号码为空";
}else if(errorCode==-42){
return "短信内容为空";
}else if(errorCode==-51){
return "短信签名格式不正确";
}else if(errorCode==-6){
return "IP限制";
}else{
return "未知错误码:"+errorCode;
}
}
}

JsonResult

package com.it.whitejotterapi.tools;

/**
* @Author: 羡羡
* @Date: 2022/05/23/08:39
* JSON统一返回
*/
public class JsonResult {
int code;
String msg;
Object data;

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

public JsonResult() {
}

public JsonResult(int code, String msg) {
this.code = code;
this.msg = msg;
}

public JsonResult(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}

@Override
public String toString() {
return "\nJsonResult{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}

service

package com.it.whitejotterapi.service;
import com.it.whitejotterapi.tools.JsonResult;
/**
* @Author: 羡羡
* @Date: 2022/05/29/11:07
*/
public interface SendMessage {
/**
* 发送短信
* @param iphone 发送的电话
* @param context 发送的内容
* @return
*/
JsonResult sendmes(String iphone,String context);
}

serviceimpl

package com.it.whitejotterapi.service.impl;
import com.it.whitejotterapi.service.SendMessage;
import com.it.whitejotterapi.tools.HttpClientUtil;
import com.it.whitejotterapi.tools.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* @Author: 羡羡
* @Date: 2022/05/29/11:08
*/
@Service
public class SendMessageImpl implements SendMessage {
/**
* 用户名
*/
@Value("${message.uid}")
private String uid;
/**
* 秘钥
*/
@Value("${message.key}")
private String key;
/**
* 发送短信
* @param iphone 发送的电话
* @param context 发送的内容
* @return
*/
@Override
public JsonResult sendmes(String iphone, String context) {
HttpClientUtil client=HttpClientUtil.getInstance();
int result = client.sendMsgUtf8(uid,key,context,iphone);
if(result>0){
return new JsonResult(200,"发送成功!");
}else{
return new JsonResult(500,client.getErrorMsg(result));
}
}
}

控制器

package com.it.whitejotterapi.controller;
import com.it.whitejotterapi.service.impl.SendEmailServiceImpl;
import com.it.whitejotterapi.service.impl.SendMessageImpl;
import com.it.whitejotterapi.tools.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: 羡羡
* @Date: 2022/05/29/10:49
*/
@RestController
public class SendEmailContoller {
/**
* 发送短信impl
*/
@Autowired
SendMessageImpl sem;
/**
* 发送短信
* @param iphone 电话
* @param context 内容
* @return
*/
@RequestMapping(path = "/sendmessage",method = RequestMethod.POST)
public JsonResult sendmes(String iphone,String context){
return sem.sendmes(iphone,context);
}
}

post请求传电话 和 发送的内容即可