JAVA 调用oauth2获取token及后续业务请求示例代码

JAVA 封装类:

package com.xrh.core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.logging.Logger;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.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 org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
 * http业务接口请求
 * @author 李小家
 *
 */
public class HttpClient4Util {

    private static final Logger logger = Logger.getLogger(HttpClient4Util.class.getName());
 
    public static String doPost(String url, Map<String, Object> paramMap) {
        return doPost(url, paramMap, null);
    }

    public static String doPost(String url, Map<String, Object> paramMap, Map<String, String> headerMap) {

        logger.info("doPost url=" + url);
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
 
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = null;
        // 配置请求参数实例
        requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                .setSocketTimeout(60000)// 设置读取数据连接超时时间
                .build();

        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头
        if (headerMap == null){
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");// "application/json"
        } else {
            for (String key : headerMap.keySet()) {
                httpPost.addHeader(key, headerMap.get(key));
            }
        }

        // 封装post请求参数
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<>();
            // 通过map集成entrySet方法获取entity
            Set<Entry<String, Object>> entrySet = paramMap.entrySet();
            // 循环遍历,获取迭代器
            Iterator<Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }

            // 为httpPost设置封装好的请求参数
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
    
    public static String requestPayload(String httpUrl, String jsonStr) {
        return requestPayload(httpUrl, jsonStr, null);
    }

    public static String requestPayload(String httpUrl, String jsonStr, Map<String, String> headerMap) {
        logger.info("httpUrl=" + httpUrl);
        logger.info("jsonStr=" + jsonStr);
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(httpUrl);
            
            // 设置请求头
            if (headerMap != null){
                for (String key : headerMap.keySet()) {
                    httpPost.addHeader(key, headerMap.get(key));
                }
            }
            
            StringEntity stringEntity = new StringEntity(jsonStr, "UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            closeableHttpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            return EntityUtils.toString(httpEntity);// 响应内容
        } catch (UnsupportedCharsetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (closeableHttpResponse != null) {
                try {
                    closeableHttpResponse.close();
                } catch (IOException e) {
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }
 
}

JAVA 调用示例:

        // 获取访问令牌
        Map paramMap = new HashMap();
        paramMap.put("client_id", "******");
        paramMap.put("client_secret", "******");
        paramMap.put("scope", "***");
        paramMap.put("grant_type", "*****");
        String result = HttpClient4Util.doPost("https://***/oauth/token", paramMap, null);
        LOGGER.info(result);

        //后续业务接口请求
        JSONObject requestJson = new JSONObject();
        requestJson.put("param1", 30);
        requestJson.put("param2", "222");
        requestJson.put("param3", "3333");

        Map headerMap = new HashMap();
        headerMap.put("Content-Type", "application/json");
        headerMap.put("Authorization", "Bearer {前面获取到的token}");

        String result2 = HttpClient4Util.requestPayload("https://***",
                requestJson.toString(), headerMap);
        LOGGER.info(result2);

 

posted @ 2021-03-12 18:23  李小加  阅读(3050)  评论(2编辑  收藏  举报