文档中心

{{item.title}}
{{subItem.title}}
{{subItemChild.title}}

< 文档中心

{{item.title}}
{{subItem.title}}
{{subItemChild.title}}

通用API

{{item.title}}
{{subItem.title}}
{{subItem.title}}
通用API >{{posName}}

{{subitem.title}}

{{subitem.uptateTime}}

{{subitem.title}}

HTTP请求工具类:ClientUtil
        package com.casic.util;
        import org.apache.commons.logging.Log;
        import org.apache.commons.logging.LogFactory;
        import org.apache.http.client.methods.*;
        import org.apache.http.client.utils.URIBuilder;
        import org.apache.http.entity.ContentType;
        import org.apache.http.entity.StringEntity;
        import org.apache.http.entity.mime.MultipartEntityBuilder;
        import org.apache.http.impl.client.CloseableHttpClient;
        import org.apache.http.impl.client.HttpClients;
        import org.apache.http.util.EntityUtils;
        
        import com.alibaba.fastjson.JSONArray;
        import com.casic.entity.Params;
        
        import java.io.File;
        import java.io.IOException;
        import java.net.URI;
        import java.util.HashMap;
        import java.util.Map;
        public class HttpClientUtil {
          private static final Log LOG = LogFactory.getLog(HttpClientUtil.class);
          private static final String APP_KEY = "appKey";// appkey
          private static final String APP_SECRET = "appSecret";// 应用秘钥
          private static final String ORDER_SECRET = "orderSecret";// 订单秘钥
          private static final String USER_NAME = "userName";// 用户名称
        
          /**
            * 获取token
            * 
            * @param url
            * @param params
            * @return
            */
          public static String getToken(String url, Params params) {
            Map map = new HashMap();
            map.put(APP_SECRET, params.getAppSecret());
            map.put(APP_KEY, params.getAppKey());
            map.put(ORDER_SECRET, params.getOrderSecret());
            map.put(USER_NAME, params.getUserName());
            return doGet(url, map);
          }
        
          /**
            * 查询采用get方式
            * 
            * @param url
            * @param param
            * @return
            */
          public static String doGet(String url, Map param) {
        
            CloseableHttpClient httpclient = HttpClients.createDefault();
        
            String resultString = "";
            CloseableHttpResponse response = null;
            try {
              URIBuilder builder = new URIBuilder(url);
              if (param != null) {
                for (String key : param.keySet()) {
                  builder.addParameter(key, param.get(key));
                }
              }
              URI uri = builder.build();
              HttpGet httpGet = new HttpGet(uri);
              response = httpclient.execute(httpGet);
              if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
              }
            } catch (Exception e) {
              LOG.error(e);
            } finally {
              try {
                if (response != null) {
                  response.close();
                }
              } catch (IOException e) {
                LOG.error(e);
              }
            }
            return resultString;
          }
        
          /**
            * 新增采用POST
            * 
            * @param url
            * @param param
            * @return
            */
          public static String doPost(String url, Map param) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
              HttpPost httpPost = new HttpPost(url);
              httpPost.setHeader("Content-Type", "application/json");
              if (param != null) {
                StringEntity se = new StringEntity(JSONArray.toJSON(param).toString(), "utf-8");
                httpPost.setEntity(se);
              }
              response = httpClient.execute(httpPost);
              resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (Exception e) {
              LOG.error(e);
            } finally {
              try {
                if (response != null) {
                  response.close();
                }
              } catch (IOException e) {
                LOG.error(e);
              }
            }
        
            return resultString;
          }
        
          /**
            * 文件上传
            * 
            * @param url
            * @param file
            * @param param
            * @return
            */
          public static String doPostOfMultipartFormData(String url, File file, Map param) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
              HttpPost httpPost = new HttpPost(url);
              MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
              if (file != null && file.exists() && file.isFile()) {
                multipartEntityBuilder.addBinaryBody("file", file);
              }
              if (param != null) {
                for (String key : param.keySet()) {
                  multipartEntityBuilder.addTextBody(key, param.get(key));
                }
              }
              httpPost.setEntity(multipartEntityBuilder.build());
              response = httpClient.execute(httpPost);
              resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (Exception e) {
              LOG.error(e);
        
            } finally {
              try {
                if (response != null) {
                  response.close();
                }
              } catch (IOException e) {
                LOG.error(e);
              }
            }
        
            return resultString;
          }
        
          /**
            * json格式POST
            * 
            * @param url
            * @param json
            * @return
            */
          public static String doPostOfJson(String url, String json) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
              HttpPost httpPost = new HttpPost(url);
              StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
              httpPost.setEntity(entity);
              response = httpClient.execute(httpPost);
              resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (Exception e) {
              LOG.error(e);
        
            } finally {
              try {
                if (response != null) {
                  response.close();
                }
              } catch (IOException e) {
                LOG.error(e);
              }
            }
        
            return resultString;
          }
        
          /**
            * json格式put
            * 
            * @param url
            * @param json
            * @return
            */
          public static String doPutOfJson(String url, String json) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
              HttpPut httpPut = new HttpPut(url);
              StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
              httpPut.setEntity(entity);
              response = httpClient.execute(httpPut);
              resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (Exception e) {
              LOG.error(e);
        
            } finally {
              try {
                if (response != null) {
                  response.close();
                }
              } catch (IOException e) {
                LOG.error(e);
              }
            }
        
            return resultString;
          }
        
          /**
            * 删除采用DELETE
            * 
            * @param url
            * @param param
            * @return
            */
          public static String doDelete(String url, Map param) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
              URIBuilder builder = new URIBuilder(url);
              if (param != null) {
                for (String key : param.keySet()) {
                  builder.addParameter(key, param.get(key));
                }
              }
              URI uri = builder.build();
              HttpDelete httpDelete = new HttpDelete(uri);
              response = httpClient.execute(httpDelete);
              resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (Exception e) {
              LOG.error(e);
        
            } finally {
              try {
                if (response != null) {
                  response.close();
                }
              } catch (IOException e) {
                LOG.error(e);
              }
            }
        
            return resultString;
          }
        
          /**
            * json方式删除
            * 
            * @param url
            * @param json
            * @return
            */
          public static String doDeleteOfJson(String url, String json) {
            class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
              public static final String METHOD_NAME = "DELETE";
        
              @SuppressWarnings("unused")
              public HttpDeleteWithBody() {
              }
        
              @SuppressWarnings("unused")
              public HttpDeleteWithBody(URI uri) {
                setURI(uri);
              }
        
              public HttpDeleteWithBody(String uri) {
                setURI(URI.create(uri));
              }
        
              @Override
              public String getMethod() {
                return METHOD_NAME;
              }
            }
        
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
              HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
              StringEntity params = new StringEntity(json, ContentType.APPLICATION_JSON);
              httpDelete.setEntity(params);
              response = httpClient.execute(httpDelete);
              resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (Exception e) {
              LOG.error(e);
        
            } finally {
              try {
                if (response != null) {
                  response.close();
                }
              } catch (IOException e) {
                LOG.error(e);
              }
            }
        
            return resultString;
          }
        }
      
客户端示例:Client
        package com.casic.cloud.api;
        
        import java.util.HashMap;
        import java.util.Map;
        
        import org.apache.commons.logging.Log;
        import org.apache.commons.logging.LogFactory;
        import org.junit.Test;
        
        import com.alibaba.fastjson.JSONArray;
        import com.casic.entity.Params;
        import com.casic.util.HttpClientUtil;
        
        public class Client
        
        {
          private static final String TOKEN_SERVER = 
        " ";// token服务
          private static final String TOKEN_URI = "api/oauthAuthorizationServer/v2/zuul/oauth/token_keys";
          private static final String APP_KEY = "";// appKey
          private static final String APP_SECRET = "";// app秘钥
          private static final String ORDER_SECRET = "";// 订单秘钥
          private static final String USER_NAME = "";// 用户名称
          private static final String API_URL = "";// api服务地址
          private static final String ACCESS_TOKEN = "accessToken";// token
          private static final String EXPIRES_TIME = "expiresTime";// token过期时间,单位秒
          private static Log logger = LogFactory.getLog(Client.class);
          private static Map tokenInfo;
          private static Params param = new Params();
        
          static {
            param.setAppKey(APP_KEY);
            param.setAppSecret(APP_SECRET);
            param.setOrderSecret(ORDER_SECRET);
            param.setUserName(USER_NAME);
            // 根据expiresTime 过期时间,要定期更新token
            tokenInfo = getToken(TOKEN_SERVER + TOKEN_URI, param);
          }
        
          // 查询采用get方式
          @Test
          public void invokeQueryApi() {
            String url = API_URL + "{uri}?access_token=" + tokenInfo.get(ACCESS_TOKEN) + "&app_key=" + APP_KEY;
            if (tokenInfo != null && Long.valueOf(tokenInfo.get(EXPIRES_TIME)) < 0) {
              tokenInfo = getToken(TOKEN_SERVER + TOKEN_URI, param);
        
            } else if (tokenInfo != null) {
              Map paramMap = new HashMap();
              String getJson = HttpClientUtil.doGet(url.replace("{uri}", "groups/10000003750027"), paramMap);
              logger.info(getJson);
        
            }
        
          }
        
          // 新增采用POST方式
          @Test
          public void invokeAddApi() {
            String url = API_URL + "{uri}?access_token=" + tokenInfo.get(ACCESS_TOKEN) + "&app_key=" + APP_KEY;
            if (tokenInfo != null && Long.valueOf(tokenInfo.get(EXPIRES_TIME)) < 0) {
              tokenInfo = getToken(TOKEN_SERVER + TOKEN_URI, param);
        
            } else if (tokenInfo != null) {
              Map paramMap = new HashMap();
              // 新增
              paramMap.clear();
              paramMap.put("name", "deviceGroup测试名称2-ry");
              String postJons = HttpClientUtil.doPost(url.replace("{uri}", "groups"), paramMap);
              logger.info(postJons);
            }
        
          }
        
          // 修改采用PUT
          @Test
          public void invokeUpdateApi() {
            String url = API_URL + "{uri}?access_token=" + tokenInfo.get(ACCESS_TOKEN) + "&app_key=" + APP_KEY;
            if (tokenInfo != null && Long.valueOf(tokenInfo.get(EXPIRES_TIME)) < 0) {
              tokenInfo = getToken(TOKEN_SERVER + TOKEN_URI, param);
        
            } else if (tokenInfo != null) {
              // 修改
              String jsonPut = "{\"id\":\"10000003750028\",\"name\":\"deviceGroup测试名称3-ry\"}";
              String putJons = HttpClientUtil.doPutOfJson(url.replace("{uri}", "groups"), jsonPut);
              logger.info(putJons);
        
            }
        
          }
        
          // 删除采用DELETE
          @Test
          public void invokeDeletApi() {
            String url = API_URL + "{uri}?access_token=" + tokenInfo.get(ACCESS_TOKEN) + "&app_key=" + APP_KEY;
            if (tokenInfo != null && Long.valueOf(tokenInfo.get(EXPIRES_TIME)) < 0) {
              tokenInfo = getToken(TOKEN_SERVER + TOKEN_URI, param);
        
            } else if (tokenInfo != null) {
              // 删除
              String jsonDelete = "{\"id\":\"10000003750028\"}";
              String deleteJons = HttpClientUtil.doDeleteOfJson(url.replace("{uri}", "groups"), jsonDelete);
              logger.info(deleteJons);
            }
        
          }
        
          /**
            * 获取token
            * 
            * @param url
            * @param param
            * @return
            */
          @SuppressWarnings("unchecked")
          public static Map getToken(String url, Params param) {
            String result = HttpClientUtil.getToken(url, param);
            Map map = JSONArray.parseObject(result, Map.class);
            Map data = null;
            if (map != null && Integer.valueOf(map.get("code").toString()) == 200) {
              data = (Map) map.get("data");
        
            }
            return data;
        
          }
        }
        
        参数对象:Params
        package com.casic.entity;
        /**
          * token参数
          * @author yong
          * @Date: 2019年7月16日 下午5:28:27
          * @version 1.0
          */
        public class Params {
          
          /**
            * @return the userName
            */
          public String getUserName() {
            return userName;
          }
        
          /**
            * @param userName the userName to set
            */
          public void setUserName(String userName) {
            this.userName = userName;
          }
        
          
        
          /**
            * @return the appKey
            */
          public String getAppKey() {
            return appKey;
          }
        
          /**
            * @param appKey the appKey to set
            */
          public void setAppKey(String appKey) {
            this.appKey = appKey;
          }
        
          /**
            * @return the orderSecret
            */
          public String getOrderSecret() {
            return orderSecret;
          }
        
          /**
            * @param orderSecret the orderSecret to set
            */
          public void setOrderSecret(String orderSecret) {
            this.orderSecret = orderSecret;
          }
        
          /**
            * @return the appSecret
            */
          public String getAppSecret() {
            return appSecret;
          }
        
          /**
            * @param appSecret the appSecret to set
            */
          public void setAppSecret(String appSecret) {
            this.appSecret = appSecret;
          }
        
        
          private String userName;
          
          private String appKey;
          
          private String orderSecret;
          
          private String appSecret;
        
        }
        
maven依赖
          <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.9</version>
          </dependency>
          <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
          </dependency>