使用HttpClient 获取第三方接口返回结果

最近需要在内网环境获取第三方接口提供的数据,只有jdk环境,没有maven环境,所以只能提前提供所需要的jar包

HttpClient 4

使用的jar包

 

 

 代码

     Request request = new Request();
        try {
            //Set the request parameters.
            //AppKey, AppSecrect, Method and Url are required parameters.
            request.setKey("071fe245-9cf6-4d75-822d-c29945a1e06a");
            request.setSecret("c6e52419-2270-4cb8-8bd4-ae7fdd01dcd5");
            request.setMethod("GET");
            request.setUrl("https://30030113-3657-4fb6-a7ef-90764239b038.apigw.cn-north-1.huaweicloud.com/app1?a=1");
            request.addHeader("Content-Type", "text/plain");
        //缺少验证
request.setBody("demo"); } catch (Exception e) { e.printStackTrace(); return; } CloseableHttpClient client = null; try { //Sign the request. HttpRequestBase signedRequest = Client.sign(request); //Send the request. client = HttpClients.custom().build(); HttpResponse response = client.execute(signedRequest); //Print the status line of the response. System.out.println(response.getStatusLine().toString()); //Print the header fields of the response. Header[] resHeaders = response.getAllHeaders(); for (Header h : resHeaders) { System.out.println(h.getName() + ":" + h.getValue()); } //Print the body of the response. HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println(System.getProperty("line.separator") + EntityUtils.toString(resEntity, "UTF-8")); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (client != null) { client.close(); } } catch (IOException e) { e.printStackTrace(); } }

 

HttpClient 5

使用jar包

 

 

 

代码

util类

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.net.URIBuilder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import main.java.com.aostarit.data.ApiServiceTest;


public class httpClientUnit {
    
     /* *
     * get请求
     * @author slx
     * @date 2019/03/13 16:51
     * @param [url, map]
     * @return HttpResult
     */
    public static HttpResult doGet(String tableName, Map<String, Object> map) throws Exception {
        CloseableHttpClient httpClient = null;
        Properties pro=new Properties();
        InputStream in = ApiServiceTest.class.getResourceAsStream("/main/resources/config/JDBC.properties");
        pro.load(in);
        // 1 创建HttpClinet,相当于打开浏览器
        httpClient = HttpClients.createDefault();
        
        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(pro.getProperty(tableName+".url"));

        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }
        
        // 2 创建httpGet对象,相当于设置url请求地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
        httpGet.addHeader("Accept","application/json");
        httpGet.addHeader("Authorization","Bearer 3893eb800a56905308236cfb63e9eb1c");
//        httpGet.addHeader("appkey",pro.getProperty(tableName+"。appkey"));
//        httpGet.addHeader("appsecret",pro.getProperty(tableName+"。appsecret"));
        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
        CloseableHttpResponse response = null;        
        
        try {
            response = httpClient.execute(httpGet);
        } catch (IOException e) {
            HttpResult httpResult = new HttpResult();
            httpResult.setCode(404);
            httpResult.setBody("接口请求失败!");
            return httpResult;
        }

        // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
        HttpResult httpResult = new HttpResult();
        // 解析数据封装HttpResult
        if (response.getEntity() != null) {
            httpResult.setCode(response.getCode());
            httpResult.setBody(EntityUtils.toString(response.getEntity(),"UTF-8"));
        } else {
            httpResult.setCode(response.getCode());
        }
        
        in.close();
        // 返回
        return httpResult;
        }
    
    public static List<Map<String, Object>> json2Map(String jsonStr) throws Exception{
           List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            Map<String, Object> mapResult = JSON.parseObject(jsonStr);
            if (mapResult.get("data") != null) {
                    //大小写返回
                   if(mapResult.get("data") != null && mapResult.get("data") != "")
                   data = JSON.parseObject(mapResult.get("data").toString());                   
                   if(mapResult.get("DATA") != null && mapResult.get("DATA") != "")
                data = JSON.parseObject(mapResult.get("DATA").toString());
                   
                //根据返回内容,转为list
                   String listStr = JSONArray.toJSONString(data.get("list"));
                   List<Object> obj = JSON.parseArray(listStr);
                   int i = 0;
                   for (Object map : obj) {
                    Map<String, Object> map2 = (Map<String, Object>) obj.get(i);
                    resultList.add(map2);
                    i ++;
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        
        return resultList;
        
    }
  
}

 

httpResult

package main.java.com.aostarit.utils;

public class HttpResult {

    // 响应的状态码
    private int code;

    // 响应的响应体
    private String body;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}

 

Test类

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import main.java.com.aostarit.utils.HttpResult;
import main.java.com.aostarit.utils.httpClientUnit;

public class ApiServiceTest {

    public static void main(String[] args) throws Exception {
        String tableName = "COMPANYINFO";

        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("param","50");
//        map.put("pagesize","1");
        map.put("offset","1");
        map.put("limit","20");
        map.put("gzzt","0");
        map.put("_t","1606353457232");
        
        HttpResult httpResult = httpClientUnit.doGet(tableName,map);

        System.out.println(httpResult.getCode());
        System.out.println(httpResult.getBody());
        List<Map<String, Object>> data= new ArrayList<Map<String,Object>>();
        if (httpResult.getCode() == 200) {
            data = httpClientUnit.json2Map(httpResult.getBody());
        }
     
    }
}

 

public static HttpResult doGet(String tableName, Map<String, Object> map) throws Exception {    CloseableHttpClient httpClient = null;    Properties pro=new Properties();        InputStream in = ApiServiceTest.class.getResourceAsStream("/main/resources/config/JDBC.properties");        pro.load(in);        // 1 创建HttpClinet,相当于打开浏览器        httpClient = HttpClients.createDefault();            // 声明URIBuilder        URIBuilder uriBuilder = new URIBuilder(pro.getProperty(tableName+".url"));
        // 判断参数map是否为非空        if (map != null) {            // 遍历参数            for (Map.Entry<String, Object> entry : map.entrySet()) {                // 设置参数                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());            }        }                // 2 创建httpGet对象,相当于设置url请求地址        HttpGet httpGet = new HttpGet(uriBuilder.build());        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");        httpGet.addHeader("Accept","application/json");        httpGet.addHeader("Authorization","Bearer 3893eb800a56905308236cfb63e9eb1c");//        httpGet.addHeader("appkey",pro.getProperty(tableName+"。appkey"));//        httpGet.addHeader("appsecret",pro.getProperty(tableName+"。appsecret"));        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求        CloseableHttpResponse response = null;                        try {            response = httpClient.execute(httpGet);        } catch (IOException e) {            HttpResult httpResult = new HttpResult();            httpResult.setCode(404);            httpResult.setBody("接口请求失败!");            return httpResult;        }
        // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果        HttpResult httpResult = new HttpResult();        // 解析数据封装HttpResult        if (response.getEntity() != null) {            httpResult.setCode(response.getCode());            httpResult.setBody(EntityUtils.toString(response.getEntity(),"UTF-8"));        } else {            httpResult.setCode(response.getCode());        }                in.close();        // 返回        return httpResult;    }        public static List<Map<String, Object>> json2Map(String jsonStr) throws Exception{       List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();    try {            Map<String, Object> data = new HashMap<String, Object>();    Map<String, Object> mapResult = JSON.parseObject(jsonStr);            if (mapResult.get("data") != null) {            //大小写返回           if(mapResult.get("data") != null && mapResult.get("data") != "")           data = JSON.parseObject(mapResult.get("data").toString());                      if(mapResult.get("DATA") != null && mapResult.get("DATA") != "")            data = JSON.parseObject(mapResult.get("DATA").toString());                   //根据返回内容,转为list           String listStr = JSONArray.toJSONString(data.get("list"));           List<Object> obj = JSON.parseArray(listStr);           int i = 0;           for (Object map : obj) {Map<String, Object> map2 = (Map<String, Object>) obj.get(i);resultList.add(map2);i ++;}            }} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}    return resultList;        }

posted @ 2020-12-02 11:37  47Knife  阅读(2060)  评论(0编辑  收藏  举报