java发送http请求获取手机验证码
Maven<!--http --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><
·
Maven
<!--http -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
随便找了一家短信验证码运营商,
对着提供的api文档
提供api需要的参数
/***
* 手机端发送信息
*
* @param mobile
* 机号码,多个号码使用","分割
* @param msg
* 短信内容
* @return 验证码
*/
public static String smsCodeSend(String mobile) throws Exception {
//用build方法来创建实例
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(Const.REST_URL);
Date day=new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String curTime = df.format(day);
//加密
String sig=MD5.md5(Const.ACCOUNT_SID+Const.AUTH_TOKEN+curTime);
//添加头部信息
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("accountSid", Const.ACCOUNT_SID));
nvps.add(new BasicNameValuePair("templateid", Const.TEMPLATEID));
nvps.add(new BasicNameValuePair("to", "186****6643"));
nvps.add(new BasicNameValuePair("timestamp", curTime));
nvps.add(new BasicNameValuePair("sig", sig));
nvps.add(new BasicNameValuePair("param", "12345"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
HttpResponse response = httpClient.execute(httpPost);
String a=EntityUtils.toString(response.getEntity(), "utf-8");
JSONObject result = new JSONObject( );
String code = (result!=null?result.get("respCode").toString():null);
String obj = (result!=null?result.get("respDesc").toString():null);
return code;
}
然后,就可以了,就是这么简单
更多推荐
已为社区贡献1条内容
所有评论(0)