// http工具类创建HttpClient对象。
// 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
// 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
// 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
// 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
// 释放连接。无论执行方法是否成功,都必须释放连接
public class HttpUtil{
public static String post(String url,List<NameValuePail> nvps) throws Exception{
HttpPost HttpPost = new HttpPost(url);
HttpPost.setEntity(new UrlEncodeFormEntity(nvps));
return execeteRequest(HttpPost);
}
public static String get(String url) throws Exception{
HttpGet httpget = new HttpGet();
return execeteRequest(httpget);
}
public static class UrlBuilder{
private StringBuilder builder;
public UrlBuilder(String url){
builder = new StringBuilder(url).append('?')
}
public UrlBuilder setParam(String name,String value){
builder.append(name)
.append('=')
.append(value)
.append('&');
return this;
}
public String build()
{
return builder.toString();
}
}
public static String execeteRequest(HttpUriRequest request) throws Exception{
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response httpClient.execute(request);
try{
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine);
HttpEntiry entity = response.getEntiry();
if(statusLine.getStatusCode()== 200){
return EntiryUtils.toString(entity,"utf-8");
}
EntiryUtils.consume(entity);
throw new HttpException(statusLine.toString());
}finally{
if(response != null){
response.close();
}
}
}
}
// 发送验证码
/**
* 发送短信验证码并保存验证码
* @param phoneNumber the user's phone number, the text message send to
* @param availableTime the value of the availableTime of the text message
*/
@Override
public void sendTextMessageAndSaveVerifyCode(String phoneNumber, Integer availableTime) {
String code = generateVerifyCode(); // 动态声明验证码
String tkey = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
HttpUtil.UrlBuilder builder = new HttpUtil.UrlBuilder(TEXT_URL); // 发送验证码的URL
builder.setParam("username", TEXT_USERNAME); // 登录账户
builder.setParam("mobile", phoneNumber); // 发送者的手机号码
builder.setParam("tkey", tkey); // 时间格式
builder.setParam("password", DigestUtils.md5Hex(DigestUtils.md5Hex(TEXT_PWD) + tkey)); // 登录用户密码
builder.setParam("content", String.format(TEXT_CONTENT, code)); // 发送短信内容
String url = builder.build(); // 构建需要发送验证码的url
try {
String res = HttpUtil.get(url);
System.out.println("textres: " + res);
if (res.indexOf("1,") == 0) {
saveCode(phoneNumber, code, availableTime);
return;
}
throw new BojiuException("发送短信失败");
} catch (Exception e) {
throw new BojiuException("发送短信失败");
}
}
第三方短信验证
最新推荐文章于 2021-05-28 20:48:22 发布