第三方接口调用httpUtils

2023-06-20,,

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

7、使用restTemplate其他请求

String[] array = list.stream().map(Dev::getS).toArray(String[]::new);
HttpHeaders httpHeader = new HttpHeaders();
httpHeader.setAll(sign);
httpHeader.setContentType(MediaType.APPLICATION_JSON_UTF8);
Map<String, Object> map = new HashMap<>();

map.put("list", array);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(map, httpHeader);
String res = restTemplate.postForObject(URL + "/api/xxx", request, String.class);
Msg body = JSONObject.parseObject(res, Msg.class);

private Map<String, String> sign() {
HashMap<String, String> map = Maps.newHashMap();
map.put("Authorization", auth.toString());
map.put("X-Xxx", hdate);

}

第三方接口调用httpUtils的相关教程结束。

《第三方接口调用httpUtils.doc》

下载本文的Word格式文档,以方便收藏与打印。