900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 14 阿里云短信Demo演示 Http的Get请求和Post请求演示 httpClient工具类演示 发送

14 阿里云短信Demo演示 Http的Get请求和Post请求演示 httpClient工具类演示 发送

时间:2018-12-12 15:15:45

相关推荐

14 阿里云短信Demo演示 Http的Get请求和Post请求演示 httpClient工具类演示 发送

阿里云短信Demo演示

一、前端部分

无前端。

二、后端部分

1、创建发送短信测试模块SmsSendDemo,不用使用骨架。

2、在pom文件中引入依赖坐标

<dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.0.3</version></dependency>

3、新建demo类SendDemo

从阿里云的demo实例中将类复制到这个demo类中。

SendDemo中全文如下:

package cn.myApplication;import monRequest;import monResponse;import com.aliyuncs.DefaultAcsClient;import com.aliyuncs.IAcsClient;import com.aliyuncs.exceptions.ClientException;import com.aliyuncs.exceptions.ServerException;import com.aliyuncs.http.MethodType;import com.aliyuncs.profile.DefaultProfile;public class SendDemo {public static void main(String[] args) {DefaultProfile profile = DefaultProfile.getProfile("default", "LTAIk********sMkU", "AkxxB****************8lgHRT********vc");//使用密钥<accessKeyId>和<accessSecret>IAcsClient client = new DefaultAcsClient(profile);CommonRequest request = new CommonRequest();//request.setProtocol(ProtocolType.HTTPS);request.setMethod(MethodType.POST);request.setDomain("");request.setVersion("-05-25");request.setAction("SendSms");request.putQueryParameter("PhoneNumbers", "198****3487"); //目标手机号码request.putQueryParameter("SignName", "国际***商系统");//申请阿里云短信时的项目名称request.putQueryParameter("TemplateCode", "SMS_*****5570");//申请的阿里云短信的模板request.putQueryParameter("TemplateParam", "{\"code\":\"12***6\"}"); //验证码(需要写成json格式)try {CommonResponse response = client.getCommonResponse(request);System.out.println(response.getData());} catch (ServerException e) {e.printStackTrace();} catch (ClientException e) {e.printStackTrace();}}}

4、运行main方法,即可在目标短信中收到信息

Http的Get请求演示

一、前端部分

不涉及前端。

二、后端部分

方便起见,直接在SmsSendDemo模块中创建Demo类。

1、创建HttpClientGetTest类

全文如下:

package cn.myApplication;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import java.io.IOException;public class HttpClientGetTest {public static void main(String[] args) {CloseableHttpClient httpClient = HttpClients.createDefault();HttpGet httpGet = new HttpGet("/s?wd=java");try {CloseableHttpResponse response = httpClient.execute(httpGet);if (response.getStatusLine().getStatusCode() == 200) {HttpEntity entity = response.getEntity();String s = EntityUtils.toString(entity, "utf-8");System.out.println(s);}} catch (IOException e) {e.printStackTrace();}}}

Http的Post请求演示

一、前端部分

不涉及前端。

二、后端部分

1、创建HttpClientPostTest类

package cn.myApplication;import org.apache.http.HttpEntity;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;public class HttpClientPostTest {public static void main(String[] args) throws UnsupportedEncodingException {CloseableHttpClient httpClient = HttpClients.createDefault();/** 此处用开源中国举例说明。添加到list集合中的数据是根据开源中国具体的访问路径而定,* 不是固定写法。具体网站需要具体分析。* */HttpPost httpPost = new HttpPost("/");ArrayList<NameValuePair> valuePairs = new ArrayList<NameValuePair>();valuePairs.add(new BasicNameValuePair("scope", "project"));valuePairs.add(new BasicNameValuePair("q", "java"));//使用UrlEncodedFormEntity将list转为entity对象UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, "utf-8");//将entity设置到httpPost中,作为访问路径的参数。httpPost.setEntity(entity);//有些网站拒绝不是浏览器发出的请求,所以需要手动设置请求头信息(从任意网站上F12看请求头即可找到,复制过来即可)httpPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");try {CloseableHttpResponse response = httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode() == 200) {HttpEntity responseEntity = response.getEntity();String s = EntityUtils.toString(responseEntity, "utf-8");System.out.println(s); //打印的是当前网页的html数据 }} catch (IOException e) {e.printStackTrace();}}}

httpClient工具类演示

一、前端部分

不涉及前端。

二、后端部分

1、复制HttpClientUtil工具类到当前模块中。(这个HttpClientUtil不是咱写的,直接复制过来的)

package cn.myApplication;import java.io.IOException;import java.security.GeneralSecurityException;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.text.ParseException;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;import .ssl.SSLContext;import .ssl.SSLException;import .ssl.SSLSession;import .ssl.SSLSocket;import .ssl.TrustManager;import .ssl.X509TrustManager;import org.apache.http.Consts;import org.apache.http.HttpEntity;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;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.client.methods.HttpUriRequest;import org.apache.http.client.protocol.HttpClientContext;import org.apache.http.conn.scheme.Scheme;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.SSLContextBuilder;import org.apache.http.conn.ssl.SSLSocketFactory;import org.apache.http.conn.ssl.TrustStrategy;import org.apache.http.conn.ssl.X509HostnameVerifier;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;/*** http请求客户端* * @author Administrator* */public class HttpClientUtil {public static HttpClientContext context = null;static {System.out.println("====================begin");context = HttpClientContext.create();}private String url;private Map<String, String> param;private int statusCode;private String content;private String xmlParam;private boolean isHttps;public boolean isHttps() {return isHttps;}public void setHttps(boolean isHttps) {this.isHttps = isHttps;}public String getXmlParam() {return xmlParam;}public void setXmlParam(String xmlParam) {this.xmlParam = xmlParam;}public HttpClientUtil(String url, Map<String, String> param) {this.url = url;this.param = param;}public HttpClientUtil(String url) {this.url = url;}public void setParameter(Map<String, String> map) {param = map;}public void addParameter(String key, String value) {if (param == null)param = new HashMap<String, String>();param.put(key, value);}public void post() throws ClientProtocolException, IOException {HttpPost http = new HttpPost(url);setEntity(http);execute(http);}public void put() throws ClientProtocolException, IOException {HttpPut http = new HttpPut(url);setEntity(http);execute(http);}public void get() throws ClientProtocolException, IOException {if (param != null) {StringBuilder url = new StringBuilder(this.url);boolean isFirst = true;for (String key : param.keySet()) {if (isFirst)url.append("?");elseurl.append("&");url.append(key).append("=").append(param.get(key));}this.url = url.toString();}HttpGet http = new HttpGet(url);execute(http);}/*** set http post,put param*/private void setEntity(HttpEntityEnclosingRequestBase http) {if (param != null) {List<NameValuePair> nvps = new LinkedList<NameValuePair>();for (String key : param.keySet())nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数}if (xmlParam != null) {http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));}}private void execute(HttpUriRequest http) throws ClientProtocolException,IOException {CloseableHttpClient httpClient = null;try {if (isHttps) {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {// 信任所有public boolean isTrusted(X509Certificate[] chain,String authType)throws CertificateException {return true;}}).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();} else {httpClient = HttpClients.createDefault();}CloseableHttpResponse response = httpClient.execute(http,context);try {if (response != null) {if (response.getStatusLine() != null)statusCode = response.getStatusLine().getStatusCode();HttpEntity entity = response.getEntity();// 响应内容content = EntityUtils.toString(entity, Consts.UTF_8);}} finally {response.close();}} catch (Exception e) {e.printStackTrace();} finally {httpClient.close();}}public int getStatusCode() {return statusCode;}public String getContent() throws ParseException, IOException {return content;}}

2、编写测试类,测试HttpClientUtilTest用来测试使用HttpClientUtil。

package cn.myApplication;import org.apache.http.client.protocol.HttpClientContext;import java.io.IOException;import java.util.HashMap;import java.util.Map;/**使用工具类来访问我们自己的项目。* 我们的项目使用了security安全框架,无法直接访问* 解决办法:* 1、在security的配置文件spring-security.xml中,在释放访问资源的配置中,添加我们将要访问的方法* 2、不使用第一种方式的话,可以在本类中先使用post方法,先将用户名和密码发送给安全框架的login。*/public class HttpClientUtilTest {public static void main(String[] args) throws Exception {HttpClientUtil httpClientUtilLogin = new HttpClientUtil("http://localhost:9101/login");Map map = new HashMap();map.put("username", "admin");map.put("password", "123456");httpClientUtilLogin.setParameter(map);httpClientUtilLogin.post();/* String loginContent = httpClientUtilLogin.getContent();//获取返回值//System.out.println(loginContent);*/HttpClientUtil httpClientUtil = new HttpClientUtil("http://localhost:9101/brand/findAll.do");httpClientUtil.get();String content = httpClientUtil.getContent();System.out.println(content);}}

附:在security的配置文件spring-security.xml中,在释放访问资源的配置中,添加我们将要访问的方法。操作如下:

发送短信模块搭建

一、前端部分

不涉及前端。

二、后端部分

新建短信发送模块sms。因为需要单独启动,所以使用骨架。

1、在pom文件中引入依赖,和tomcat配置

2、在web.xml中配置springmvc的基本配置

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="/2001/XMLSchema-instance"xmlns="/xml/ns/javaee"xsi:schemaLocation="/xml/ns/javaee /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>*.do</url-pattern></servlet-mapping></web-app>

3、在resources中需要有两个配置文件

application.properties中写的是阿里云短信服务的密钥

全文如下:

accessKeyId=LTA***********jNGaccessKeySecret=AMlN************************0bAsq

springmvc.xml中设置的是加载上面的配置文件,以及包扫描等。

全文如下:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance" xmlns:p="/schema/p"xmlns:context="/schema/context"xmlns:dubbo="/schema/dubbo" xmlns:mvc="/schema/mvc"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans.xsd/schema/mvc /schema/mvc/spring-mvc.xsd/schema/dubbo /schema/dubbo/dubbo.xsd/schema/context /schema/context/spring-context.xsd"><context:property-placeholder location="classpath:config/application.properties" /><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><context:component-scan base-package="cn.myApplication.sms"/></beans>

4、在java文件夹中创建controller类SmsController(配置RequestMapping,可以通过ip地址和端口号以及访问方法直接使用这个类的功能)

SmsController全文如下:

import monRequest;import monResponse;import com.aliyuncs.DefaultAcsClient;import com.aliyuncs.IAcsClient;import com.aliyuncs.exceptions.ClientException;import com.aliyuncs.exceptions.ServerException;import com.aliyuncs.http.MethodType;import com.aliyuncs.profile.DefaultProfile;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class SmsController {/*@Value("${accessKeyId}")private String accessKeyId;*/@RequestMapping("/sms")public void sendSms(String phone,String code){DefaultProfile profile = DefaultProfile.getProfile("default", "LTAIk********sMkU", "AkxxBk*************Hk*******9yvc");IAcsClient client = new DefaultAcsClient(profile);CommonRequest request = new CommonRequest();//request.setProtocol(ProtocolType.HTTPS);request.setMethod(MethodType.POST);request.setDomain("");request.setVersion("-05-25");request.setAction("SendSms");request.putQueryParameter("RegionId", "cn-hangzhou");request.putQueryParameter("PhoneNumbers", phone);//电话由调用者传过来request.putQueryParameter("SignName", "国际*****系统");request.putQueryParameter("TemplateCode", "SMS_*******70");request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");//验证码由调用者传过来try {CommonResponse response = client.getCommonResponse(request);System.out.println(response.getData());//这里输出的是返回信息// {"Message":"OK","RequestId":"8D1EB85C-D1C6-401F-8387-6AC68ACE69FF","BizId":"694609952912473540^0","Code":"OK"}} catch (ServerException e) {e.printStackTrace();} catch (ClientException e) {e.printStackTrace();}}}

搭建用户中心模块

新建模块

1、interface中不使用骨架,其余两个使用骨架

2、在service实现类中,web.xml配置文件如下:

3、在service的resources中引入配置文件

applicationContext-activemq.xml今天不用。

applicationContext-service.xml中配置的是访问dubbo的地址等。

4、在user-web模块中引入静态文件

web.xml全文如下:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="/2001/XMLSchema-instance"xmlns="/xml/ns/javaee"xsi:schemaLocation="/xml/ns/javaee /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><filter><filter-name>SpringEncodingFilter</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>SpringEncodingFilter</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>*.do</url-pattern></servlet-mapping><welcome-file-list><welcome-file>search.html</welcome-file></welcome-file-list></web-app>

在web模块的resources中引入配置文件

springmvc.xml全文如下:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance" xmlns:p="/schema/p"xmlns:context="/schema/context"xmlns:dubbo="/schema/dubbo" xmlns:mvc="/schema/mvc"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans.xsd/schema/mvc /schema/mvc/spring-mvc.xsd/schema/dubbo /schema/dubbo/dubbo.xsd/schema/context /schema/context/spring-context.xsd"><mvc:annotation-driven><mvc:message-converters register-defaults="true"><beanclass="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><!-- 引用dubbo 服务 --><dubbo:application name="MyApplication-user-web" /><dubbo:registry address="zookeeper://192.168.25.128:2181" /><dubbo:annotation package="com.MyApplication.user.controller" /></beans>

在web模块的pom文件中设置tomcat

<build><plugins><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.2</version><configuration><!-- 指定端口 --><port>9106</port><!-- 请求路径 --><path>/</path></configuration></plugin></plugins></build>

一、前端部分

不涉及。

二、后端部分

不涉及。

完成user注册基本功能

一、前端部分

1、页面绑定模型和save方法以及smsSend方法等

2、在js文件中controller.js文件中定义对应的方法

3、在js文件的service.js中完成请求的发送

二、后端部分

1、pom文件中引入依赖

其他的需要什么引入什么。

注意:将redis的配置文件和HttpClientUtil工具类放在common模块的util文件夹下,所以还需要引入common模块。

2、common内引入的文件和类的说明

3、在web模块中定义UserController类。

4、在user_interface接口中添加方法

5、在UserServiceImpl实现类中实现接口中的方法

引入userMapper和redisTemplate

实现add添加方法

实现发送验证码的sendSms方法

实现checkSmsCode方法

14 阿里云短信Demo演示 Http的Get请求和Post请求演示 httpClient工具类演示 发送短信模块搭建 搭建用户中心模块 完成user注册基本功能 验证码存入redis 短信验证码注册

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。