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; }