zoukankan      html  css  js  c++  java
  • httpclient调用接口

    使用httpclient调用接口相比webservice轻量,和c#的webapi还有些区别,下面温习一下项目中使用httpclient调用接口。

    1、建立HttpClientUtil类定义基本的属性和方法

      1 import com.alibaba.fastjson.JSON;
      2 import org.apache.commons.lang.StringUtils;
      3 import org.apache.http.HttpEntity;
      4 import org.apache.http.HttpResponse;
      5 import org.apache.http.NameValuePair;
      6 import org.apache.http.client.config.RequestConfig;
      7 import org.apache.http.client.entity.UrlEncodedFormEntity;
      8 import org.apache.http.client.methods.CloseableHttpResponse;
      9 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
     10 import org.apache.http.client.methods.HttpGet;
     11 import org.apache.http.client.methods.HttpPost;
     12 import org.apache.http.client.methods.HttpPut;
     13 import org.apache.http.entity.StringEntity;
     14 import org.apache.http.impl.client.CloseableHttpClient;
     15 import org.apache.http.impl.client.HttpClientBuilder;
     16 import org.apache.http.message.BasicNameValuePair;
     17 import org.apache.http.util.EntityUtils;
     18 import org.slf4j.Logger;
     19 import org.slf4j.LoggerFactory;
     20 
     21 import java.net.URI;
     22 import java.util.ArrayList;
     23 import java.util.HashMap;
     24 import java.util.List;
     25 import java.util.Map;
     26 
     27 @SuppressWarnings("all")
     28 public class HttpClientUtil {
     29 
     30     /** logger */
     31     private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);
     32 
     33     private static final CloseableHttpClient httpClient;
     34     public static final String CHARSET = "UTF-8";
     35 
     36     static {
     37         RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(15000).build();
     38         httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
     39     }
     40 
     41     public static String doGet(String url, Map<String, String> params) {
     42         return doGet(url, params, CHARSET);
     43     }
     44 
     45     public static String doPost(String url, Map<String, String> params) {
     46         return doPost(url, params, CHARSET);
     47     }
     48 
     49     public static String doPostWithJSON(String url, Object params) throws Exception {
     50         return doPostWithJSON(url, params, CHARSET);
     51     }
     52 
     53     public static String doPutWithJSON(String url, Object params) throws Exception {
     54         return doPutWithJSON(url, params, CHARSET);
     55     }
     56 
     57     public static String doDeleteWithJSON(String url, Object params) throws Exception {
     58         return doDeleteWithJSON(url, params, CHARSET);
     59     }
     60 
     61 
     62     /**
     63      * HTTP Get 获取内容
     64      *
     65      * @param url     请求的url地址 ?之前的地址
     66      * @param params  请求的参数
     67      * @param charset 编码格式
     68      * @return 页面内容
     69      */
     70     public static String doGet(String url, Map<String, String> params, String charset) {
     71         if (StringUtils.isBlank(url)) {
     72             return null;
     73         }
     74         try {
     75             if (params != null && !params.isEmpty()) {
     76                 List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
     77                 for (Map.Entry<String, String> entry : params.entrySet()) {
     78                     String value = entry.getValue();
     79                     if (value != null) {
     80                         pairs.add(new BasicNameValuePair(entry.getKey(), value));
     81                     }
     82                 }
     83                 url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
     84             }
     85             HttpGet httpGet = new HttpGet(url);
     86             CloseableHttpResponse response = httpClient.execute(httpGet);
     87             int statusCode = response.getStatusLine().getStatusCode();
     88             if (statusCode != 200) {
     89                 httpGet.abort();
     90                 throw new RuntimeException("HttpClient,error status code :" + statusCode);
     91             }
     92             HttpEntity entity = response.getEntity();
     93             String result = null;
     94             if (entity != null) {
     95                 result = EntityUtils.toString(entity, "utf-8");
     96             }
     97             EntityUtils.consume(entity);
     98             response.close();
     99             return result;
    100         } catch (Exception e) {
    101             e.printStackTrace();
    102         }
    103         return null;
    104     }
    105 
    106     /**
    107      * HTTP Post 获取内容
    108      *
    109      * @param url     请求的url地址 ?之前的地址
    110      * @param params  请求的参数
    111      * @param charset 编码格式
    112      * @return 页面内容
    113      */
    114     public static String doPost(String url, Map<String, String> params, String charset) {
    115         if (StringUtils.isBlank(url)) {
    116             return null;
    117         }
    118         try {
    119             List<NameValuePair> pairs = null;
    120             if (params != null && !params.isEmpty()) {
    121                 pairs = new ArrayList<>(params.size());
    122                 for (Map.Entry<String, String> entry : params.entrySet()) {
    123                     String value = entry.getValue();
    124                     if (value != null) {
    125                         pairs.add(new BasicNameValuePair(entry.getKey(), value));
    126                     }
    127                 }
    128             }
    129             HttpPost httpPost = new HttpPost(url);
    130             if (pairs != null && pairs.size() > 0) {
    131                 httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
    132             }
    133             CloseableHttpResponse response = httpClient.execute(httpPost);
    134             int statusCode = response.getStatusLine().getStatusCode();
    135             if (statusCode != 200) {
    136                 httpPost.abort();
    137                 throw new RuntimeException("HttpClient,error status code :" + statusCode);
    138             }
    139             HttpEntity entity = response.getEntity();
    140             String result = null;
    141             if (entity != null) {
    142                 result = EntityUtils.toString(entity, "utf-8");
    143             }
    144             EntityUtils.consume(entity);
    145             response.close();
    146             return result;
    147         } catch (Exception e) {
    148             e.printStackTrace();
    149         }
    150         return null;
    151     }
    152 
    153     /**
    154      * json post
    155      *
    156      *
    157      * @date: 2017-10-27 16:14:47
    158      */
    159     public static String doPostWithJSON(String url, Object params, String charset) throws Exception {
    160         LOGGER.debug("httpClient doPostWithJSON url:	" + url);
    161 
    162         HttpPost httpPost = new HttpPost(url);
    163 
    164         StringEntity entity = new StringEntity(JSON.toJSONString(params), charset);
    165         entity.setContentEncoding(charset);
    166         entity.setContentType("application/json");
    167         httpPost.setEntity(entity);
    168         LOGGER.debug("httpClient doPostWithJSON params:	" + JSON.toJSONString(params));
    169 
    170         HttpResponse response = httpClient.execute(httpPost);
    171         int statusCode = response.getStatusLine().getStatusCode();
    172         if (statusCode != 200) {
    173             httpPost.abort();
    174             throw new RuntimeException("HttpClient,error status code :" + statusCode);
    175         }
    176         HttpEntity responseEntity = response.getEntity();
    177         String respContent = EntityUtils.toString(responseEntity, charset);
    178         LOGGER.debug("httpClient doPostWithJSON respContent:	" + respContent);
    179         return respContent;
    180     }
    181 
    182     /**
    183      * @Title: doPutWithJSON
    184      * @Description:
    185      * @param: url
    186      * @param: params
    187      * @param: charset
    188      * @return: java.lang.String
    189      * @throws:
    190      * 
    191      */
    192     public static String doPutWithJSON(String url, Object params, String charset) throws Exception {
    193         LOGGER.debug("httpClient doPutWithJSON url:	" + url);
    194         HttpPut httpPut = new HttpPut(url);
    195 
    196         StringEntity entity = new StringEntity(JSON.toJSONString(params), charset);
    197         entity.setContentEncoding(charset);
    198         entity.setContentType("application/json");
    199         httpPut.setEntity(entity);
    200         LOGGER.debug("httpClient doPutWithJSON params:	" + JSON.toJSONString(params));
    201 
    202         HttpResponse response = httpClient.execute(httpPut);
    203         int statusCode = response.getStatusLine().getStatusCode();
    204         if (statusCode != 200) {
    205             httpPut.abort();
    206             throw new RuntimeException("HttpClient,error status code :" + statusCode);
    207         }
    208         HttpEntity responseEntity = response.getEntity();
    209         String respContent = EntityUtils.toString(responseEntity, charset);
    210         LOGGER.debug("httpClient doPutWithJSON respContent:	" + respContent);
    211         return respContent;
    212     }
    213 
    214     /**
    215      * @Title: doDeleteWithJSON
    216      * @Description:
    217      * @param: url
    218      * @param: params
    219      * @param: charset
    220      * @return: java.lang.String
    221      * @throws:
    222      * 
    223      */
    224     public static String doDeleteWithJSON(String url, Object params, String charset) throws Exception {
    225         /**
    226          * 没有现成的delete可以带json的,自己实现一个,参考HttpPost的实现
    227          */
    228         class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
    229             public static final String METHOD_NAME = "DELETE";
    230 
    231             @SuppressWarnings("unused")
    232             public HttpDeleteWithBody() {
    233             }
    234 
    235             @SuppressWarnings("unused")
    236             public HttpDeleteWithBody(URI uri) {
    237                 setURI(uri);
    238             }
    239 
    240             public HttpDeleteWithBody(String uri) {
    241                 setURI(URI.create(uri));
    242             }
    243 
    244             public String getMethod() {
    245                 return METHOD_NAME;
    246             }
    247         }
    248         LOGGER.debug("httpClient doDeleteWithJSON url:	" + url);
    249         HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
    250 
    251         StringEntity entity = new StringEntity(JSON.toJSONString(params), charset);
    252         entity.setContentEncoding(charset);
    253         entity.setContentType("application/json");
    254         httpDelete.setEntity(entity);
    255         LOGGER.debug("httpClient doDeleteWithJSON params:	" + JSON.toJSONString(params));
    256 
    257         HttpResponse response = httpClient.execute(httpDelete);
    258         int statusCode = response.getStatusLine().getStatusCode();
    259         if (statusCode != 200) {
    260             httpDelete.abort();
    261             throw new RuntimeException("HttpClient,error status code :" + statusCode);
    262         }
    263         HttpEntity responseEntity = response.getEntity();
    264         String respContent = EntityUtils.toString(responseEntity, charset);
    265         LOGGER.debug("httpClient doDeleteWithJSON respContent:	" + respContent);
    266         return respContent;
    267     }
    268 
    269     /**
    270      * 获取新建柜员参数
    271      *
    272      * @param tlrIdt
    273      * @return
    274      */
    275     public static Map<String, String> getCiftlrAddParam(String tlrIdt) {
    276         Map<String, String> params = new HashMap<String, String>();
    277         params.put("tlrIdt", tlrIdt);//柜员号
    278         params.put("tlrNum", tlrIdt.substring(2, tlrIdt.length()));//柜员编号
    279         params.put("bdtTdtTyp", "0000100 - 国泰安银行总行营业部");
    280         params.put("bdtTdt", "0000100");
    281         params.put("bdtTyp", "05");
    282         params.put("tlrNam", "信贷员" + Integer.parseInt(tlrIdt));//用户名
    283         params.put("tlrTyp", "1");
    284         params.put("sgnPwd", "666666");
    285         params.put("sgnPdc", "666666");
    286         params.put("tlrRak", "5");
    287         params.put("aut1", "000005@6");
    288         params.put("autMa1", "000005");
    289         params.put("mngCl1", "6");
    290         params.put("aut2", "000006@7");
    291         params.put("autMa2", "000006");
    292         params.put("mngCl2", "7");
    293         params.put("ftxFlg", "Y");
    294         params.put("cbxFlg", "1");
    295         params.put("eftDat", "2015-01-19");
    296         params.put("expDat", "2099-01-01");
    297         params.put("uptTlr", "000001");
    298         params.put("recSts", "P");
    299         params.put("uptDat", "2015-01-19 00:00:00");
    300         params.put("citCde", "00");
    301         return params;
    302 
    303     }
    304 
    305     /**
    306      * 获取柜员匹配参数
    307      *
    308      * @param tlrIdt
    309      * @return
    310      */
    311     public static Map<String, String> getUserroleAddParam(String tlrIdt) {
    312         Map<String, String> params = new HashMap<String, String>();
    313         params.put("usr_rol", "0007,00070002;0008,00080002;");
    314         params.put("tlr_idt", tlrIdt);
    315         params.put("radio_0007", "11");
    316         params.put("radio_0008", "11");
    317         return params;
    318     }
    319 
    320 
    321 }
    View Code

    2、在项目中调用

    1 ScoreApi scoreApi = traintestService.getExeScoreListApi(trainTest.getId(), 0);
    2                      
    3                     String s = HttpClientUtil.doPostWithJSON(sPath+score, scoreApi);
    4                     ResultMsg resultMsg = JSON.parseObject(s, ResultMsg.class);
    5                     if(resultMsg.getResult() == 1){
    6                         throw new RuntimeException(resultMsg.getExplain());
    7                     }
    View Code
    1 String url = hostAddr+"/common/projectInfo/getBasicItemsApi";
    2         Map params = new HashMap<>();
    3         params.put("teacherId", "2");
    4         String str = HttpClientUtil.doPost(url, params);
    View Code
  • 相关阅读:
    mysql的存储过程
    一份php高级工程师的面试题,我每天看一点点
    php的常用函数(持续更新)
    php 中文字符串截取
    php递归遍历文件目录
    ajax timeout 断网处理
    angular 刷新问题
    angular state中templateUrl 路径的模板
    angular请求传递不了数据
    截取字符串 substring substr slice
  • 原文地址:https://www.cnblogs.com/songStar/p/9639157.html
Copyright © 2011-2022 走看看