本文作者:DurkBlue

使用org.apache.httpcomponents进行与外部数据通信拉取外部接口API数据推荐

使用org.apache.httpcomponents进行与外部数据通信拉取外部接口API数据摘要:            HttpComponents,主要是提供对htt...

   

        HttpComponents,主要是提供对http服务器的访问功能,目前已经集成了一个单独的项目,可见http服务器的访问绝非易事。

    在某些时候可能需要通过程序来访问这别人的接口,比如从别人的接口中获取一些数据。如果对方仅仅是一个很简单的页面,那我们的程序会很简单,。但是考虑到一些服务授权的问 题,很多公司提供的页面往往并不是可以通过一个简单的URL就可以访问的,而必须经过注册然后登录后方可使用提供服务的页面,这个时候就涉及到 COOKIE问题的处理我们知道目前流行的动态网页技术例如ASP、JSP无不是通过COOKIE来处理会话信息的。为了使我们的程序能使用别人所提供的服务页面,就要求程序首先登录后再访问服务页面!再比如通过HTTP来上传文件呢?

  HttpComponents项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。通过它可以让原来很头疼的事情现在轻松的解决,例如你不再管是HTTP或者HTTPS的通讯方式,告诉它你想使用HTTPS方式,剩下的事情交给 httpclient替你完成。

 

    导入相关的依赖

    pom.xml


                <dependency>
          <groupId>org.apache.httpcomponents</groupId>
              <artifactId>httpcore</artifactId>
              <version>4.4.10</version>
            </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5</version>
        </dependency>


    博主粗略的封装了发送get与post请求


/**
    *
发送请求
   
* @param url 请求接口
   
* @param data 携带的请求数据
   
* @param method 请求方式GETPOST
   
* @param connectTimeoutMs 三次握手行为时所设置的超时时间单位毫秒
   
* @param readTimeoutMs 读写时间,当连接成功时,所执行的操作限时,单位毫秒
   
* @return 字符串相应数据
   
* @throws Exception 异常
   
*/
   
private String request(String url, String data, String method, int connectTimeoutMs, int readTimeoutMs) throws Exception{
       logger.info("请求程序开始");
       
Exception exception =  null;

       
try{
           String result = requestOnce(url, data, method, connectTimeoutMs, readTimeoutMs);
           
logger.info("相应结果:{}", result);
           
return result;
       
}catch (UnknownHostException ex){
           // dns解析错误,可能域名不存在
           
ex.printStackTrace();
           
exception = ex;
       
}catch (ConnectTimeoutException ex){
           exception = ex;
           
ex.printStackTrace();
       
}catch (SocketTimeoutException ex){
           exception = ex;
           
ex.printStackTrace();
       
}catch (Exception ex){
           ex.printStackTrace();
           
exception = ex;
       
}
       throw exception;
   
}

   /**
    *
请求一次
   
* @param url 接口url
    *
@param data 请求参数json
    *
@param connectTimeoutMs 连接超时时间单位毫秒
   
* @param readTimeoutMs 读取超时时间单位毫秒
   
* @return
   
* @throws Exception
    */
   
private String requestOnce(String url,String data, String method, int connectTimeoutMs, int readTimeoutMs) throws Exception{
       BasicHttpClientConnectionManager connManager;
       
logger.info("开始发送请求");
       
connManager = new BasicHttpClientConnectionManager(
               RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory())
                       .register("https", SSLConnectionSocketFactory.getSocketFactory())
                       .build(),
               
null,
               
null,
               
null
       );

       
HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
       
HttpResponse httpResponse = null;
       
HttpEntity httpEntity = null;
       
if(method.equals("POST")){
           HttpPost httpPost = new HttpPost(url);
           
logger.info("发送POST请求url{}",url);
           
// 指定超时策略
           
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
           
httpPost.setConfig(requestConfig);
           
if(StringUtils.isNotEmpty(data)){
               StringEntity postEntity = new StringEntity(data, "UTF-8");
               
httpPost.addHeader("Content-Type","application/json");
               
httpPost.setEntity(postEntity);
           
}
           // 向服务器发送请求
           
httpResponse = httpClient.execute(httpPost);
           
httpEntity = httpResponse.getEntity();


       
}else if(method.equals("GET")){
           if(StringUtils.isNotEmpty(data)){
               Map<String, Object> params = JSON.parseObject(data, new TypeReference<Map<String, Object>>(){});
               
// 获取map集合迭代器
               
Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
               
String getPar = "";// 键值对
               
while (iterator.hasNext()){
                   Map.Entry<String, Object> entry = iterator.next();// 指针指向下一行
                   
String key = entry.getKey();
                   
Object value = entry.getValue();
                   
getPar += key + "=" + value + "&";
               
}
               url = url + "?" + getPar;
           
}
           //url = url + "?" + getPar;
           logger.info("发送GET请求url{}",url);
           
HttpGet httpGet = new HttpGet(url);
           
// 指定超时策略
           
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
           
httpGet.setConfig(requestConfig);
           
httpResponse = httpClient.execute(httpGet);
           
if (httpResponse != null) {
               httpEntity = httpResponse.getEntity();
//                if (httpEntity != null) {
//                    result = EntityUtils.toString(resEntity, "utf-8");
//                    JSONObject pa = JSONObject.parseObject(result);
//                    if (pa.get("code").equals(200)) {
//                        String data = pa.getString("data");
//                        // 返回值
//                        JSONObject pa1 = JSONObject.parseObject(data);
//                        // 取价格
//                        price = pa1.get("discountedPrice");
//                    }
//                }
           }

       }

       return EntityUtils.toString(httpEntity, "UTF-8");

   
}

    

 

使用org.apache.httpcomponents进行与外部数据通信拉取外部接口API数据  第1张


        结果数据集处理部分


        

@Override
public List<Map<String, String>> getSuperviseDepartLists() throws ServiceException {
   // 获取督办系统域名
   
String url = configService.selectConfigByKey("app.supervise.handle.domain");
   
try {
       String result = request(url + "/adminapi/article.article/getDept","","GET", 6000,8000);
       
Map<String,Object> dataMap = JSON.parseObject(result,new TypeReference<Map<String,Object>>(){});
       
List<Map<String, String>> list = JSON.parseObject(dataMap.get("data").toString(), new TypeReference<ArrayList<Map<String, String>>>(){});
       
System.err.println(result);
       
System.err.println(dataMap);
       
System.err.println(list);
       
return list;
   
} catch (Exception e) {
       throw new ServiceException(e.getMessage());
   
}
}


@Override
public Map<String, Object> getAccountList(Integer pageSize, Integer page,Map<String, Object> searchMaps) throws LaiKeAPIException {
   // 设置接口返回数据
   
Map<String, Object> dataList = new HashMap<>();

   
// 构造请求参数
   
Map<String, Object> req = new HashMap<>();
   
req.put("pageSize",pageSize);// 每页拉取大小
   
Integer pageIndex = (page - 1) * pageSize;
   
req.put("pageIndex", pageIndex);
   
// 是否加入查询条件
   
if(searchMaps != null){
       req.put("searchParameter",searchMaps);
   
}
   String url = reqIp + "/hpt/v2/Accounts/List";
   
String reqToJSONStr = JSONObject.toJSONString(req);
   
try {
       logger.info("请求参数{}", reqToJSONStr);
       
String result = request(url,reqToJSONStr,"POST", 6000,8000);
       
dataList = JSON.parseObject(result,new TypeReference<Map<String,Object>>(){});
       
return dataList;
   
} catch (Exception e) {
       logger.info("异常信息{}",e.getMessage());
       
throw new RuntimeException(e);
   
}
}


此篇文章由DurkBlue发布,转载一下需要注明来处
文章投稿或转载声明

来源:DurkBlue版权归原作者所有,转载请保留出处。本站文章发布于 03-07
温馨提示:文章内容系作者个人观点,不代表DurkBlue博客对其观点赞同或支持。

赞(0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

阅读
分享

发表评论取消回复

快捷回复:
AddoilApplauseBadlaughBombCoffeeFabulousFacepalmFecesFrownHeyhaInsidiousKeepFightingNoProbPigHeadShockedSinistersmileSlapSocialSweatTolaughWatermelonWittyWowYeahYellowdog

评论列表 (暂无评论,139人围观)参与讨论

还没有评论,来说两句吧...