zoukankan      html  css  js  c++  java
  • Java Http POST/GET 情求

    POST:

        //返回体
        public static final String RESPONCE_BODY = "responceBody";
    
        //URL
        public static final String FINAL_URL = "url";
    
        //发送信息
        public static final String SEND_BODY = "sendBody";
    
    /**
         * post请求
         *
         * @param url         url地址
         * @param entityParam 参数
         * @return
         */
        public static HashMap post(String url, Entity entityParam) {
            HashMap resultMap = new HashMap<String, String>();
            String resultStr = "";
            log.info("执行信息体|url:" + url + " ||json:" + entityParam);
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                url = URLDecoder.decode(url, "UTF-8");
                HttpPost method = new HttpPost(url);
                if (null != entityParam) {
                    StringEntity entity = new StringEntity(entityParam.toJson(), "UTF-8");
                    entity.setContentType("application/json;charset=UTF-8");
                    method.setEntity(entity);
                }
                HttpResponse result = httpClient.execute(method);
                log.info("返回码:" + result.getStatusLine().getStatusCode());
                resultStr = EntityUtils.toString(result.getEntity());
                log.info("返回内容:" + resultStr);
            } catch (Exception e) {
                log.error("错误信息:", e);
            }
            resultMap.put(SEND_BODY, entityParam.toJson());
            resultMap.put(RESPONCE_BODY, resultStr);
            resultMap.put(FINAL_URL, url);
            return resultMap;
        }

    GET 情求

        /**
         * get请求
         *
         * @param url
         */
        public static CloseableHttpResponse getRequest(String url, Map<String, String> headMap) {
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(toUTF_8(url, "utf-8"));
                if (!CollectionUtils.isEmpty(headMap)) {
                    headMap.forEach((k, v) -> httpGet.setHeader(k, v));
                }
                response = httpClient.execute(httpGet);
                response.close();
            } catch (Exception e) {
                log.info("get请求出错:", e);
            }
            return response;
        }

    可以参考:https://blog.csdn.net/qq9808/article/details/78320816

  • 相关阅读:
    05-3. 六度空间 (PAT)
    05-2. Saving James Bond
    05-1. List Components (PAT)
    04-3. Huffman Codes (PAT)
    04-2. File Transfer (PAT)
    04-1. Root of AVL Tree (PAT)
    03-3. Tree Traversals Again (PAT)
    03-2. List Leaves (PAT)
    03-1. 二分法求多项式单根(PAT)
    CDH Namenode自动切换(active-standby)
  • 原文地址:https://www.cnblogs.com/huanghuanghui/p/11263738.html
Copyright © 2011-2022 走看看