package com.project.common.sms;
|
|
import com.project.common.constant.Constants;
|
import org.apache.http.HttpEntity;
|
import org.apache.http.NameValuePair;
|
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.HttpPost;
|
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.util.ArrayList;
|
import java.util.HashMap;
|
import java.util.List;
|
import java.util.Map;
|
|
/**
|
* 短信http接口的java代码调用示例
|
* 基于Apache HttpClient 4.3
|
* @author Mr.Zhao
|
*/
|
|
public class YPSmsApi {
|
|
/**
|
* 请求地址
|
*/
|
private static final String YP_SMS_URI = "http://yunpian.com/v1/sms/send.json";
|
|
/**
|
* KEY
|
*/
|
private static final String API_KEY = "faf531146ca1e38abacd3862fb3fc32b";
|
|
/**
|
* 签名
|
*/
|
private static final String SIGN = "【金明源】";
|
|
/**
|
* 验证码模板
|
*/
|
public static final String VERIFY_CODE_TEMPLATE = "您的验证码是{}";
|
|
/**
|
* 审批通知模板
|
*/
|
public static final String CHECK_NOTICE_TEMPLATE = SIGN + "{}提交了执法申请单,请您及时审批!";
|
|
/**
|
* 审批通过模板
|
*/
|
public static final String CHECK_PASS_TEMPLATE = SIGN + "您提交的执法申请单已审批通过,请您及时查看!";
|
|
|
|
|
/**
|
* 发送短信
|
* @param mobile 接受的手机号
|
* @param msg 短信内容
|
*/
|
public static String sendSms(String mobile, String msg)
|
{
|
Map<String, String> params = new HashMap<>(3);
|
params.put("apikey", API_KEY);
|
params.put("text", msg);
|
params.put("mobile", mobile);
|
return post(YP_SMS_URI, params);
|
}
|
|
public static void main(String[] args) {
|
sendSms("18537821663", "【金明源】您的验证码是1234");
|
}
|
|
|
/**
|
* 基于HttpClient 4.3的通用POST方法
|
*
|
* @param url 提交的URL
|
* @param paramsMap 提交<参数,值>Map
|
* @return 提交响应
|
*/
|
public static String post(String url, Map<String, String> paramsMap)
|
{
|
CloseableHttpClient client = HttpClients.createDefault();
|
String responseText = "";
|
CloseableHttpResponse response = null;
|
try {
|
HttpPost method = new HttpPost(url);
|
if (paramsMap != null) {
|
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
|
for (Map.Entry<String, String> param : paramsMap.entrySet()) {
|
NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
|
paramList.add(pair);
|
}
|
method.setEntity(new UrlEncodedFormEntity(paramList, Constants.UTF8));
|
}
|
response = client.execute(method);
|
HttpEntity entity = response.getEntity();
|
if (entity != null) {
|
responseText = EntityUtils.toString(entity);
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
} finally {
|
try {
|
if (response != null) {
|
response.close();
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
System.out.println(responseText);//此处打印在console后,会给出一个IP地址
|
return responseText;
|
}
|
}
|