沈阳做企业网站哪家好,设计师常用的网站,网络推广外包公司哪家好,外贸网站建设团队目录山东鼎信API工具类随机验证码工具类进行测试Pom依赖(可以先导入依赖)创建controllerSmsServiceSmsServiceImplswagger测试(也可以使用postman)山东鼎信API工具类
山东鼎信短信官网 找到java的Api#xff0c;复制下来 适当改了一下#xff0c;为了调用(类名SmsUtils)
p…
目录山东鼎信API工具类随机验证码工具类进行测试Pom依赖(可以先导入依赖)创建controllerSmsServiceSmsServiceImplswagger测试(也可以使用postman)山东鼎信API工具类
山东鼎信短信官网 找到java的Api复制下来 适当改了一下为了调用(类名SmsUtils)
public static void sendShortMessage(String phoneNumbers,String param){String host http://dingxin.market.alicloudapi.com;String path /dx/sendSms;String method POST;String appcode 你的 appcode;MapString, String headers new HashMapString, String();//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105headers.put(Authorization, APPCODE appcode);MapString, String querys new HashMapString, String();querys.put(mobile, phoneNumbers);querys.put(param, code:param);querys.put(tpl_id, TP1711063);MapString, String bodys new HashMapString, String();try {/*** 重要提示如下:* HttpUtils请从* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java* 下载** 相应的依赖请参照* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml*/HttpResponse response HttpUtils.doPost(host, path, method, headers, querys, bodys);System.out.println(response.toString());//获取response的body//System.out.println(EntityUtils.toString(response.getEntity()));} catch (Exception e) {e.printStackTrace();}}
代码中的appcode在控制台的云市场 然后会发现HttpUtils爆红然后也给了我们提示 然后进入网址把代码拷贝下来就行了
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;public class HttpUtils {/*** get* * param host* param path* param method* param headers* param querys* return* throws Exception*/public static HttpResponse doGet(String host, String path, String method, MapString, String headers, MapString, String querys)throws Exception { HttpClient httpClient wrapClient(host);HttpGet request new HttpGet(buildUrl(host, path, querys));for (Map.EntryString, String e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}return httpClient.execute(request);}/*** post form* * param host* param path* param method* param headers* param querys* param bodys* return* throws Exception*/public static HttpResponse doPost(String host, String path, String method, MapString, String headers, MapString, String querys, MapString, String bodys)throws Exception { HttpClient httpClient wrapClient(host);HttpPost request new HttpPost(buildUrl(host, path, querys));for (Map.EntryString, String e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (bodys ! null) {ListNameValuePair nameValuePairList new ArrayListNameValuePair();for (String key : bodys.keySet()) {nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));}UrlEncodedFormEntity formEntity new UrlEncodedFormEntity(nameValuePairList, utf-8);formEntity.setContentType(application/x-www-form-urlencoded; charsetUTF-8);request.setEntity(formEntity);}return httpClient.execute(request);} /*** Post String* * param host* param path* param method* param headers* param querys* param body* return* throws Exception*/public static HttpResponse doPost(String host, String path, String method, MapString, String headers, MapString, String querys, String body)throws Exception { HttpClient httpClient wrapClient(host);HttpPost request new HttpPost(buildUrl(host, path, querys));for (Map.EntryString, String e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (StringUtils.isNotBlank(body)) {request.setEntity(new StringEntity(body, utf-8));}return httpClient.execute(request);}/*** Post stream* * param host* param path* param method* param headers* param querys* param body* return* throws Exception*/public static HttpResponse doPost(String host, String path, String method, MapString, String headers, MapString, String querys, byte[] body)throws Exception { HttpClient httpClient wrapClient(host);HttpPost request new HttpPost(buildUrl(host, path, querys));for (Map.EntryString, String e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body ! null) {request.setEntity(new ByteArrayEntity(body));}return httpClient.execute(request);}/*** Put String* param host* param path* param method* param headers* param querys* param body* return* throws Exception*/public static HttpResponse doPut(String host, String path, String method, MapString, String headers, MapString, String querys, String body)throws Exception { HttpClient httpClient wrapClient(host);HttpPut request new HttpPut(buildUrl(host, path, querys));for (Map.EntryString, String e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (StringUtils.isNotBlank(body)) {request.setEntity(new StringEntity(body, utf-8));}return httpClient.execute(request);}/*** Put stream* param host* param path* param method* param headers* param querys* param body* return* throws Exception*/public static HttpResponse doPut(String host, String path, String method, MapString, String headers, MapString, String querys, byte[] body)throws Exception { HttpClient httpClient wrapClient(host);HttpPut request new HttpPut(buildUrl(host, path, querys));for (Map.EntryString, String e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body ! null) {request.setEntity(new ByteArrayEntity(body));}return httpClient.execute(request);}/*** Delete* * param host* param path* param method* param headers* param querys* return* throws Exception*/public static HttpResponse doDelete(String host, String path, String method, MapString, String headers, MapString, String querys)throws Exception { HttpClient httpClient wrapClient(host);HttpDelete request new HttpDelete(buildUrl(host, path, querys));for (Map.EntryString, String e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}return httpClient.execute(request);}private static String buildUrl(String host, String path, MapString, String querys) throws UnsupportedEncodingException {StringBuilder sbUrl new StringBuilder();sbUrl.append(host);if (!StringUtils.isBlank(path)) {sbUrl.append(path);}if (null ! querys) {StringBuilder sbQuery new StringBuilder();for (Map.EntryString, String query : querys.entrySet()) {if (0 sbQuery.length()) {sbQuery.append();}if (StringUtils.isBlank(query.getKey()) !StringUtils.isBlank(query.getValue())) {sbQuery.append(query.getValue());}if (!StringUtils.isBlank(query.getKey())) {sbQuery.append(query.getKey());if (!StringUtils.isBlank(query.getValue())) {sbQuery.append();sbQuery.append(URLEncoder.encode(query.getValue(), utf-8));} }}if (0 sbQuery.length()) {sbUrl.append(?).append(sbQuery);}}return sbUrl.toString();}private static HttpClient wrapClient(String host) {HttpClient httpClient new DefaultHttpClient();if (host.startsWith(https://)) {sslClient(httpClient);}return httpClient;}private static void sslClient(HttpClient httpClient) {try {SSLContext ctx SSLContext.getInstance(TLS);X509TrustManager tm new X509TrustManager() {public X509Certificate[] getAcceptedIssuers() {return null;}public void checkClientTrusted(X509Certificate[] xcs, String str) {}public void checkServerTrusted(X509Certificate[] xcs, String str) {}};ctx.init(null, new TrustManager[] { tm }, null);SSLSocketFactory ssf new SSLSocketFactory(ctx);ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);ClientConnectionManager ccm httpClient.getConnectionManager();SchemeRegistry registry ccm.getSchemeRegistry();registry.register(new Scheme(https, 443, ssf));} catch (KeyManagementException ex) {throw new RuntimeException(ex);} catch (NoSuchAlgorithmException ex) {throw new RuntimeException(ex);}}
}随机验证码工具类
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;/*** 获取随机数* * author qianyi**/
public class RandomUtil {private static final Random random new Random();private static final DecimalFormat fourdf new DecimalFormat(0000);private static final DecimalFormat sixdf new DecimalFormat(000000);public static String getFourBitRandom() {return fourdf.format(random.nextInt(10000));}public static String getSixBitRandom() {return sixdf.format(random.nextInt(1000000));}/*** 给定数组抽取n个数据* param list* param n* return*/public static ArrayList getRandom(List list, int n) {Random random new Random();HashMapObject, Object hashMap new HashMapObject, Object();// 生成随机数字并存入HashMapfor (int i 0; i list.size(); i) {int number random.nextInt(100) 1;hashMap.put(number, i);}// 从HashMap导入数组Object[] robjs hashMap.values().toArray();ArrayList r new ArrayList();// 遍历数组并打印数据for (int i 0; i n; i) {r.add(list.get((int) robjs[i]));System.out.print(list.get((int) robjs[i]) \t);}System.out.print(\n);return r;}
}
进行测试
Pom依赖(可以先导入依赖) dependenciesdependencygroupIdcom.alibaba/groupIdartifactIdfastjson/artifactIdversion1.2.15/version/dependencydependencygroupIdorg.apache.httpcomponents/groupIdartifactIdhttpclient/artifactIdversion4.2.1/version/dependencydependencygroupIdorg.apache.httpcomponents/groupIdartifactIdhttpcore/artifactIdversion4.2.1/version/dependencydependencygroupIdcommons-lang/groupIdartifactIdcommons-lang/artifactIdversion2.6/version/dependency/dependencies创建controller
import com.donglin.commonutils.R;
import com.donglin.smsservice.service.SmsService;
import com.donglin.smsservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;Api(description 短息发送)
RestController
RequestMapping(/edusms/sms)
CrossOrigin //跨域
public class SmsApiController {Autowiredprivate SmsService smsService;Autowiredprivate RedisTemplateString,String redisTemplate;ApiOperation(value 短信发送)GetMapping(send/{phone})public R sendSmsPhone(PathVariable String phone){String code redisTemplate.opsForValue().get(phone);if(!StringUtils.isEmpty(code))return R.ok();code RandomUtil.getFourBitRandom();boolean isSend smsService.send(phone, code);if(isSend) {redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);return R.ok();} else {return R.error().message(发送短信失败);}}
}
SmsService
public interface SmsService {boolean send(String phone, String code);
}
SmsServiceImpl
import com.donglin.smsservice.service.SmsService;
import com.donglin.smsservice.utils.SmsUtils;
import org.springframework.stereotype.Service;import java.rmi.ServerException;Service
public class SmsServiceImpl implements SmsService {Overridepublic boolean send(String phone, String code) {try {SmsUtils.sendShortMessage(phone,code);System.out.println(phone phone);System.out.println(code code);return true;} catch (Exception e) {e.printStackTrace();return false;}}
}
swagger测试(也可以使用postman)