14. HttpClient的使用+傳送簡訊
阿新 • • 發佈:2018-12-22
技術上:
1、 httpClient遠端呼叫技術
2、 使用Java程式碼發簡訊
3、 呼叫阿里雲通訊(阿里大於)傳送簡訊
業務:完成使用者註冊
1 HttpClient的使用
1.1 常用的遠端呼叫技術:
1、socket 套接字 效率特別高 開發特麻煩,
2、Webservice xml 傳統公司使用比較多,比較穩定效率相對快一點
3、hessian
4、httpClient json 多用於網際網路公司 稍微稍微簡潔點
5、dubbo
1.2 httpClient 的demo
需要的依賴:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
1.2.1 Get請求不帶引數
public static void main(String[] args) throws Exception { // https://www.baidu.com/s?ie=UTF-8&wd=httpClient // 1:相當於開啟瀏覽器 CloseableHttpClient httpClient = HttpClients.createDefault(); // 2:建立一個get的請求方式 HttpGet httpGet = new HttpGet("http://www.baidu.com/"); // 3:執行了ge t請求 CloseableHttpResponse response = httpClient.execute(httpGet); // 4:獲取返回的資料 // 200:正常 // 404:找不到資源 // 500:伺服器內部錯誤 // 400:引數問題 // 302:重定向 // 304:快取 // 403:Forbidden if( response.getStatusLine().getStatusCode()==200){// 如果狀態碼是200 表示正常返回了 // 把返回的內容轉成字串 String content = EntityUtils.toString(response.getEntity(), "utf-8"); System.out.println(content); } }
1.2.2 Get請求帶引數:
1.2.3 Post請求不帶引數
1.2.4 Post請求帶引數
1.2.5 使用工具類
public static void main(String[] args) throws Exception {
HttpClient httpClient = new HttpClient("http://localhost:8081/brand/findPage");
// int pageNo, int pageSize
httpClient.addParameter("pageNo","1");
httpClient.addParameter("pageSize","3");
httpClient.post();
String content = httpClient.getContent();
System.out.println(content);
}
2 阿里雲通訊的使用
www.aliyun.com
需要申請賬號,但是阿里雲通訊目前關閉了個人賬號的申請
注意阿里雲通訊中需要申請簽名和模板
3 建立一個傳送簡訊的閘道器
3.1 建立專案拷貝配置檔案
3.2 配置檔案的內容
Web.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- 解決post亂碼 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定載入的配置檔案 ,通過引數contextConfigLocation載入-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Springmvc.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:config/application.properties" />
<context:component-scan base-package="com.pyg.sms"/>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json"/>
<property name="features">
<array>
<value>WriteMapNullValue</value>
<value>WriteDateUseDateFormat</value>
</array>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--放行靜態資源-->
<mvc:default-servlet-handler/>
</beans>
Pom.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>pyg_parent</artifactId>
<groupId>com.pyg</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>pyg_sms</artifactId>
<dependencies>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.2.5</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!-- 指定埠 -->
<port>7788</port>
<!-- 請求路徑 -->
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.3 參考阿里雲通訊的程式碼建立SMSController
@RestController
@RequestMapping("/sms")
public class SmsController {
//產品名稱:雲通訊簡訊API產品,開發者無需替換
static final String product = "Dysmsapi";
//產品域名,開發者無需替換
static final String domain = "dysmsapi.aliyuncs.com";
@Value("${accessKeyId}")
private String accessKeyId;
@Value("${accessKeySecret}")
private String accessKeySecret;
@RequestMapping("/sendSms")
public Map sendSms(String phoneNumbers,String signName,String templateCode,String templateParam){
SendSmsResponse response = null;
try {
//可自助調整超時時間
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暫不支援region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
//組裝請求物件-具體描述見控制檯-文件部分內容
SendSmsRequest request = new SendSmsRequest();
//必填:待發送手機號
// request.setPhoneNumbers("18703448120");
request.setPhoneNumbers(phoneNumbers);
//必填:簡訊簽名-可在簡訊控制檯中找到
// request.setSignName("品位優雅購物");
request.setSignName(signName);
//必填:簡訊模板-可在簡訊控制檯中找到
request.setTemplateCode(templateCode);
// request.setTemplateCode("SMS_130926832");
//可選:模板中的變數替換JSON串,如模板內容為"親愛的${name},您的驗證碼為${code}"時,此處的值為
// 您的驗證碼為:${code},該驗證碼 5 分鐘內有效,請勿洩漏於他人
request.setTemplateParam(templateParam);
// request.setTemplateParam("{\"code\":\"3234\"}");
//選填-上行簡訊擴充套件碼(無特殊需求使用者請忽略此欄位)
//request.setSmsUpExtendCode("90997");
//可選:outId為提供給業務方擴充套件欄位,最終在簡訊回執訊息中將此值帶回給呼叫者
request.setOutId("yourOutId");
//hint 此處可能會丟擲異常,注意catch
response = acsClient.getAcsResponse(request);
Map map = new HashMap();
map.put("code",response.getCode());
map.put("message",response.getMessage());
map.put("requestid",response.getRequestId());
map.put("bizid",response.getBizId());
return map;
} catch (ClientException e) {
e.printStackTrace();
return null;
}
}
3.4 使用httpClient工具類測試
public static void main(String[] args) throws Exception {
HttpClient httpClient = new HttpClient("http://127.0.0.1:7788/sms/sendSms");
// (String phoneNumbers,String signName,String templateCode,String templateParam)
httpClient.addParameter("phoneNumbers","XXXXXXXXXXX");
httpClient.addParameter("signName","品位優雅購物");
httpClient.addParameter("templateCode","SMS_130926832");
String numeric = RandomStringUtils.randomNumeric(4);
System.out.println(numeric);
httpClient.addParameter("templateParam","{\"code\":\""+numeric+"\"}");
httpClient.post();
System.out.println(httpClient.getContent());
}
4 完成使用者的註冊
4.1 分析
4.2 建立專案
傳送簡訊驗證碼的service程式碼
@Autowired
private RedisTemplate redisTemplate;
@Override
public void sendSms(String phone) throws Exception {
// 使用httpClient傳送簡訊
HttpClient httpClient = new HttpClient("http://127.0.0.1:7788/sms/sendSms");
// (String phoneNumbers,String signName,String templateCode,String templateParam)
httpClient.addParameter("phoneNumbers",phone);
httpClient.addParameter("signName","品位優雅購物");
httpClient.addParameter("templateCode","SMS_130926832");
String numeric = RandomStringUtils.randomNumeric(4);
System.out.println(numeric);
httpClient.addParameter("templateParam","{\"code\":\""+numeric+"\"}");
httpClient.post();
System.out.println(httpClient.getContent());
// redisTemplate.boundValueOps("sms_"+phone).set(numeric,5, TimeUnit.MINUTES);
// 把驗證碼放入到redis中
redisTemplate.boundValueOps("sms_"+phone).set(numeric,30, TimeUnit.SECONDS);
}
註冊時的service程式碼:
@Override
public void add(TbUser user, String code) {
String numeric = (String) redisTemplate.boundValueOps("sms_" + user.getPhone()).get();
if(numeric==null){
throw new RuntimeException("驗證碼已失效");
}
if(!numeric.equals(code)){
throw new RuntimeException("驗證碼輸入有誤");
}
// 處理預設值
String password = user.getPassword(); //明文
password = DigestUtils.md5Hex(password); //通過MD5加密
user.setPassword(password);
user.setCreated(new Date());
user.setUpdated(new Date());
//`password` varchar(32) NOT NULL COMMENT '密碼,加密儲存',
// `created` datetime NOT NULL COMMENT '建立時間',
// `updated` datetime NOT NULL,
//`source_type` varchar(1) DEFAULT NULL COMMENT '會員來源:1:PC,2:H5,3:Android,4:IOS,5:WeChat',
userMapper.insert(user);
// 驗證碼使用後就可以清除了
redisTemplate.delete("sms_" + user.getPhone());
}