使用HttpClientUtil工具类调用短信接口

HttpClientUtil工具类调用短信接口

  1. 调用短信接口
      /*调用短信接口开始*/
            String url = "xxxxxxxxxxxxxxxxxxxx";
            Map<String,String> params = new HashMap<>();
            params.put("account","7552");
            params.put("mobile",model.getRisenusPhone());
            params.put("text", "您的验证码是" + key);

            params.put("sign","M2NlOGQ0MzBhYjFlOTBlZjcwOWJkN2Y1NzhhNWUwMTE=");
            params.put("extend","");

            try {
                ArrayList<String> resultParams = new ArrayList<>();
                resultParams.add("code");
                resultMap = HttpClientUtil.invokeHttp(url, HttpClientUtil.HTTP_POST, params,resultParams);
            } catch (IOException e) {
                e.printStackTrace();
            }
     /*调用短信接口结束*/
  1. HttpClientUtil工具类
package com.hw.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hew
 */
public class HttpClientUtil {

    public static String HTTP_GET = "GET";
    public static String HTTP_POST = "POST";

    public static Map<String, String> invokeHttp(String url,
                                                 String method,
                                                 Map<String, String> paramMap,
                                                 List<String> returnParamList) throws UnsupportedOperationException, IOException {        //1. 创建HttpClient对象和响应对象
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        //2. 判断请求方法是get还是post
        if (StringUtils.equalsIgnoreCase(method, HTTP_GET)) {
            //2.1 如果是get请求,要拼接请求url的参数
            StringBuilder urlSb = new StringBuilder(url);
            int paramIndex = 0;
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                //get请求要追加参数,中间有一个?
                if (paramIndex == 0) {
                    urlSb.append("?");
                }
                //拼接参数
                urlSb.append(entry.getKey() + "=" + entry.getValue() + "&");
            }
            //前面在拼接参数时最后多了一个&,应去掉
            urlSb.delete(urlSb.length() - 1, urlSb.length());
            HttpGet get = new HttpGet(urlSb.toString());
            //2.2 让HttpClient去发送get请求,得到响应
            response = client.execute(get);
        }else if (StringUtils.equalsIgnoreCase(method, HTTP_POST)) {
            HttpPost post = new HttpPost(url);
            //2.3 如果是post请求,要构造虚拟表单,并封装参数
//            List<NameValuePair> paramList = new ArrayList<>();
//            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
//                paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
//            }
            //2.4 设置请求正文的编码
            //UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(paramList, "UTF-8");

            String s = JSONObject.toJSON(paramMap).toString();
            StringEntity paramEntity = new StringEntity(s,"UTF-8");
            paramEntity.setContentEncoding("UTF-8");
            post.setHeader("Content-type", "application/json");
            post.setEntity(paramEntity);

            //2.5 让HttpClient去发送post请求,得到响应
            response = client.execute(post);
        }else {
            //其他请求类型不支持
            throw new RuntimeException("对不起,该请求方式不支持!");
        }
        //3. 提取响应正文,并封装成Map
        InputStream is = response.getEntity().getContent();
        Map<String, String> returnMap = new LinkedHashMap<>();
        String ret = IOUtils.toString(is, "UTF-8");
        //循环正则表达式匹配(因为有多个参数,无法预处理Pattern)
        /*for (String param : returnParamList) {
            Pattern pattern = Pattern.compile(param + ":['\"]?.+['\"]?");
            Matcher matcher = pattern.matcher(ret);
            while (matcher.find()) {
                String keyAndValue = matcher.group();
                String value = keyAndValue.substring(keyAndValue.indexOf("\"") + 1, keyAndValue.lastIndexOf("\""));
                returnMap.put(param, value);
            }
            //如果没有匹配到,则put进空串(jdk8的方法)
            returnMap.putIfAbsent(param, "");
        }*/
        returnMap = (Map<String, String>) JSONObject.parse(ret);
        return returnMap;
    }

    public static String invokeHttp1(String url, String method, Map<String, Object> paramMap, List<String> returnParamList) throws UnsupportedOperationException, IOException {        //1. 创建HttpClient对象和响应对象
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        //2. 判断请求方法是get还是post
        if (StringUtils.equalsIgnoreCase(method, HTTP_GET)) {
            //2.1 如果是get请求,要拼接请求url的参数
            StringBuilder urlSb = new StringBuilder(url);
            int paramIndex = 0;
            for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                //get请求要追加参数,中间有一个?
                if (paramIndex == 0) {
                    urlSb.append("?");
                }
                //拼接参数
                urlSb.append(entry.getKey() + "=" + entry.getValue() + "&");
            }
            //前面在拼接参数时最后多了一个&,应去掉
            urlSb.delete(urlSb.length() - 1, urlSb.length());
            HttpGet get = new HttpGet(urlSb.toString());
            //2.2 让HttpClient去发送get请求,得到响应
            response = client.execute(get);
        }else if (StringUtils.equalsIgnoreCase(method, HTTP_POST)) {
            HttpPost post = new HttpPost(url);
            //2.3 如果是post请求,要构造虚拟表单,并封装参数
//            List<NameValuePair> paramList = new ArrayList<>();
//            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
//                paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
//            }
            //2.4 设置请求正文的编码
            //UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(paramList, "UTF-8");

            String s = JSONObject.toJSON(paramMap).toString();
            System.out.println(s);
            StringEntity paramEntity = new StringEntity(s,"UTF-8");
            paramEntity.setContentEncoding("UTF-8");
            post.setHeader("Content-type", "application/json");
            post.setEntity(paramEntity);

            //2.5 让HttpClient去发送post请求,得到响应
            response = client.execute(post);
        }else {
            //其他请求类型不支持
            throw new RuntimeException("对不起,该请求方式不支持!");
        }
        //3. 提取响应正文,并封装成Map
        InputStream is = response.getEntity().getContent();
        String result = IOUtils.toString(is, "UTF-8");
        return result;
    }

}

注意对应引入的坐标

  1. fastjson包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
  1. commons.io包
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
  1. commons.lang3包
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.2</version>
        </dependency>
  1. http.client包
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.4</version>
        </dependency>
发布了33 篇原创文章 · 获赞 2 · 访问量 4727

猜你喜欢

转载自blog.csdn.net/qq_36778310/article/details/104523054