1.GET 请求
public static JSONObject getHttpGetResp(String url, String authorization, String title) { HttpGet httpGet = new HttpGet(url); String resp = getHttpResp(httpGet,authorization, title); return StringUtils.isEmpty(resp) ? null : JSONObject.parseObject(resp); }
2. POST 请求
public static JSONObject getHttpPostResp(String url, String authorization, StringEntity strEntity) { HttpPost httpPost = new HttpPost(url); if (Objects.nonNull(strEntity)) { httpPost.setEntity(strEntity); } String resp = getHttpResp(httpPost,authorization, ""); return StringUtils.isEmpty(resp) ? null : JSONObject.parseObject(resp); }
3. PATCH 请求
public static String getHttpPatchResp(String url, String authorization, StringEntity strEntity){ HttpPatch httpPatch = new HttpPatch(url); if (Objects.nonNull(strEntity)) { httpPatch.setEntity(strEntity); } return getHttpResp(httpPatch, authorization, ""); }
4. DELETE 请求
public static String getHttpDelResp(String url, String authorization, StringEntity strEntity){ HttpDelete httpDelete = new HttpDelete(url); return getHttpResp(httpDelete, authorization, ""); }
5. PUT 请求
public static String getHttpPutResp(String url, String authorization, StringEntity strEntity){ HttpPut httpPut = new HttpPut(url); if (Objects.nonNull(strEntity)) { httpPut.setEntity(strEntity); } return getHttpResp(httpPut,authorization, ""); }
6. 请求方法
private static String getHttpResp(HttpUriRequest var, String authorization, String text){ HttpClient client = HttpClients.createDefault(); var.setHeader("Authorization", authorization); var.setHeader("Content-type", MediaType.APPLICATION_JSON_UTF8_VALUE); String resp = null; try { HttpResponse response = client.execute(var); if (Objects.nonNull(response)) { HttpEntity entity = response.getEntity(); if (Objects.nonNull(entity)) { resp = EntityUtils.toString(entity, "utf-8"); log.info("{}结果:{}", text, resp); } } } catch (Exception e) { log.error("{}请求异常", agenda, e); } return resp; }
标签:调用,String,httpUtils,url,resp,接口,strEntity,static,authorization From: https://www.cnblogs.com/eternality/p/16806109.html