今日目标:
完成HTTPClient会GET和POST请求
在阿里云网站中注册短信功能 阿里云通信/阿里大于
自己手动编写之前品优购写的接口 品优购短信平台
能在工程中使用HTTPClient调用短信接口
完成用户注册功能
一.HttpClient的get和post请求
HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP协议最新的版本和建议。
HttpClient 提供的主要的功能
(1)实现了所有 HTTP 的方法(GET,POST,PUT,DELETE 等)
(2)支持自动转向
(3)支持 HTTPS 协议
(4)支持代理服务器等
我们之前所用的 solrj 中就封装了 HttpClient
1.get请求
导包 httpclient
基于无参数的请求
public static void main(String[] args) throws IOException {
// 1、模拟打开浏览器 HttpClients
CloseableHttpClient httpClient = HttpClients.createDefault();
// 2、设置请求对象 HttpGet
HttpGet httpGet = new HttpGet("https://www.baidu.com");
// 3、发起请求
CloseableHttpResponse response = httpClient.execute(httpGet);
// 4、基于状态码判断,如果请求成功,返回请求结果 EntityUtils
if (response.getStatusLine().getStatusCode()==200){
HttpEntity entity = response.getEntity();
//打印
System.out.println(EntityUtils.toString(entity,"utf-8"));
}
// 5、关闭资源
httpClient.close();
}
基于有参数的请求:
HttpGet httpGet = new HttpGet("http://www.baidu.com/s?wd=solr");
另一参数拼接的方式:
URIBuilder uri = new URIBuilder("http://www.baidu.com/s?").setParameter("wd","solr");
HttpGet httpGet = new HttpGet(String.valueOf(uri));
2.post请求
我们无法通过post请求抓取百度的信息,会出现302重定向,所以我们通过抓取开源中国的信息
注意:一定要设置头信息,如果不设置会导致,403,所以一定加入自己浏览器的头信息
public static void main(String[] args) throws IOException, URISyntaxException {
// 1、模拟打开浏览器 HttpClients
CloseableHttpClient httpClient = HttpClients.createDefault();
// 2、设置请求对象 HttpGet
HttpPost httpPost = new HttpPost("https://www.oschina.net/");
//开源中国,为防止恶意网站的攻击,需要设置请求头信息,才能进行访问
httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
// 3、发起请求
CloseableHttpResponse response = httpClient.execute(httpPost);
// 4、基于状态码判断,如果请求成功,返回请求结果 EntityUtils
if (response.getStatusLine().getStatusCode()==200){
HttpEntity entity = response.getEntity();
//打印
System.out.println(EntityUtils.toString(entity,"utf-8"));
}
// 5、关闭资源
httpClient.close();
}
设置带参数的post请求
2、设置请求对象 HttpGet
HttpPost httpPost = new HttpPost("https://www.oschina.net/");
//如果通过post携带参数,可以通过封装两个参数
List<NameValuePair> paramerters = new ArrayList<NameValuePair>();
//设置两个post参数,
paramerters.add(new BasicNameValuePair("scope","project"));
paramerters.add(new BasicNameValuePair("q","java"));
//构造一个form表单实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramerters,"UTF-8");
httpPost.setEntity(formEntity);
//开源中国,为防止恶意网站的攻击,需要设置请求头信息,才能进行访问
httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
二.阿里云网站注册短信功能
1.注册账号
2.登陆系统
3.进入控制台
4.申请签名
5.申请模板
6.创建accessKey
下载SDK-demo测试能否收发短信
1.首先我们导入官方提供的demo
2.导入jar
3.替换我们的accesskey信息
一些必填项,我们必须填写,都有注释
手机号 签名 模板 等
成功返回的信息
运行我们就可以咋我们自己的手机上看到验证码
三.搭建项目的短信收发平台
搭建自己项目发送短信的工程,因为可以其他模块也能用到
1.开发接口文档的编写:
接口文档:
一般包含:请求地址、请求参数列表、响应参数列表
开发中接口文档一定要会写
四.用户的注册功能
1.搭建我们需要的user工程 interface service web
思路分析:
1.输入的密码通过前台js校验
2.输入电话号码,调用接口完成短信发送,
3.通过redis存储验证码
4.登陆的时候,从redis中取出判断是否与输入的验证码一致
/**
* 发送验证码
* @param phone
*/
@Override
public void sendSmsCode(String phone) throws IOException, ParseException {
//1.随机成功六位数字验证码
int num =(int)(Math.random()*9+1);
String smsCode = RandomStringUtils.randomNumeric(5);
smsCode=num+smsCode;
//2.将生成的验证码存到redis中
redisTemplate.boundValueOps(phone).set(smsCode,5L, TimeUnit.MINUTES);
//3.调用短信发送的接口进行发送
HttpClient httpClient = new HttpClient("http://localhost:7788/sms/sendSms.do");
httpClient.addParameter("phoneNumbers",phone);
httpClient.addParameter("signName","品优购");
httpClient.addParameter("templateCode","SMS_123738164");
httpClient.addParameter("param","{\"code\":"+smsCode+"}");
//发送
httpClient.post();
//获取返回的消息
String content = httpClient.getContent();
System.out.println(content);
if (content==null){
throw new RuntimeException("调用接口失败");
}
}
@Override
public boolean checkSmsCode(String phone, String smsCode) {
//从redis中获取验证码
String sysCode = (String) redisTemplate.boundValueOps(phone).get();
//判断
if (sysCode==null){//取不到过期了
return false;
}
if (!sysCode.equals(smsCode)){
return false;
}
return true;
}
controller层
/**
* 增加
* @param user
* @return
*/
@RequestMapping("/add")
public Result add(@RequestBody TbUser user,String smsCode){
try {
//校验验证码是否正确
boolean result = userService.checkSmsCode(user.getPhone(),smsCode);
if (result==false){
return new Result(false,"验证码无效");
}
userService.add(user);
return new Result(true, "增加成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "增加失败");
}
}
/**
* 发送验证码
*/
@RequestMapping("/sendSmsCode")
public Result sendSmsCode(String phone){
try {
userService.sendSmsCode(phone);
return new Result(true, "发送成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "发送失败");
}
}
前台:
//用户注册
$scope.register=function(){
//两次输入密码是否一致
if($scope.entity.password!=$scope.entity.rePassword){
alert("两侧输入的密码不一致...,请重新输入");
}
userService.add($scope.entity,$scope.smsCode).success(
function(response){
if(response.success){
//跳转到index页面
location.href="login.html"
}else{
alert(response.message);
}
}
);
}
//发送短信验证码
$scope.sendSmsCode=function () {
userService.sendSmsCode($scope.entity.phone).success(function (response) {
//无论成功与否,都提示是否正常发送
alert(response.message);
})
}
service层
//增加
this.add=function(entity,smsCode){
return $http.post('user/add.do?smsCode='+smsCode,entity );
}