RestTemplate远程调用工具类

RestTemplate远程服务调用工具类封装,后期使用 可直接用

需注入RestTemplate

包是 import org.springframework.web.client.RestTemplate;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpRequestUtils {

    private final static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);

    /**
     * 发送GET请求,无headers
     */
    public static String get(RestTemplate restTemplate, String url) {
        return exchange(restTemplate, url, HttpMethod.GET, null, "", MediaType.APPLICATION_FORM_URLENCODED);
    }

    /**
     * 发送GET请求,有headers
     */
    public static String get(RestTemplate restTemplate, String url, HashMap<String, String> headersMap) {
        return exchange(restTemplate, url, HttpMethod.GET, headersMap, "", null);
    }

    public static String delete(RestTemplate restTemplate, String url) {
        return exchange(restTemplate, url, HttpMethod.DELETE, null, "", MediaType.APPLICATION_FORM_URLENCODED);
    }

    /**
     * 发送参数为FormData格式的Post请求
     *
     * @param restTemplate
     * @param url
     * @param headersMap
     * @param formParams
     * @return
     */
    public static String postByForm(RestTemplate restTemplate, String url, HashMap<String, String> headersMap, MultiValueMap<String, String> formParams) {
        return exchange(restTemplate, url, HttpMethod.POST, headersMap, formParams, MediaType.APPLICATION_FORM_URLENCODED);
    }

    /**
     * 发送参数为JSON格式的Post请求
     *
     * @param restTemplate
     * @param url
     * @param headersMap
     * @param jsonParams
     * @return
     */
    public static String postByJson(RestTemplate restTemplate, String url, HashMap<String, String> headersMap, String jsonParams) {
        return exchange(restTemplate, url, HttpMethod.POST, headersMap, jsonParams, MediaType.APPLICATION_JSON);
    }

    public static String putByJson(RestTemplate restTemplate, String url, HashMap<String, String> headersMap, String jsonParams) {
        return exchange(restTemplate, url, HttpMethod.PUT, headersMap, jsonParams, MediaType.APPLICATION_JSON);
    }

    private static <T> String exchange(RestTemplate restTemplate, String url, HttpMethod method, HashMap<String, String> headersMap, T params, MediaType mediaType) {
        if (restTemplate == null) {
            restTemplate = new RestTemplate();
        }
        HttpHeaders headers = new HttpHeaders();
        if (headersMap != null && headersMap.size() > 0) {
            Set<Map.Entry<String, String>> entries = headersMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                headers.add(entry.getKey(), entry.getValue());
            }
        }
        if (mediaType != null) {
            headers.setContentType(mediaType);
        }
        HttpEntity<T> entity = new HttpEntity<>(params, headers);
        logger.info("发送请求:" + url);
        logger.info("参数:" + params);
        ResponseEntity<String> responseResult = restTemplate.exchange(url, method, entity, String.class);
        logger.info("执行结果:" + responseResult);
        return responseResult.getBody();
    }

//拼装请求路径
    public static String getHttpUrl(String networkProtocol, String ip, Integer port, String suffix) {
        return networkProtocol + ip + ":" + port + suffix;
    }
//拼装请求路径
    public static String getHttpUrl(String networkProtocol, String ip, String port, String suffix) {
        return networkProtocol + ip + ":" + port + suffix;
    }

}

调用使用  简单举例 记录

注入restTemplate

@Autowired
private RestTemplate restTemplate;

1. 发送GET请求,无headers

String httpUrl = HttpRequestUtils.getHttpUrl("http", "127.0.0.1", 9010, "/tree/test");
String body = HttpRequestUtils.get(restTemplate, httpUrl);
return JSONObject.parseObject(body, Result.class);

2.发送GET请求,有headers

String httpUrl = HttpRequestUtils.getHttpUrl("http", "127.0.0.1", 9001, "/resourcesApproval/getReviewersByApprovalType");
httpUrl = httpUrl + String.format("?approvalType=%s&userId=%s", approvalType, userId);
HashMap<String, String> headersMap = new HashMap<>();
headersMap.put("token", getCookie());
String body = HttpRequestUtils.get(restTemplate, httpUrl, headersMap);
JSONObject actResult = JSONObject.parseObject(body);
Integer code = actResult.getInteger("code");
if (500 == code) {
    String message = actResult.getString("message");
    throw new RestfulException(Result.ERROR, "获取审批人失败:" + message);
}
String data = actResult.getString("data");
List<User4> Users = JSONArray.parseArray(data, User4.class);

3.发送参数为FormData格式的Post请求

String httpUrl = HttpRequestUtils.getHttpUrl("http", "127.0.0.1", 9010, "/storageConfig/createTest");
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("projectTeamId", 参数1);
params.add("projectTeamName", 参数2);
String body = HttpRequestUtils.postByForm(restTemplate, httpUrl, null, params);
JSONObject content1 = JSONObject.parseObject(body);

4.发送参数为JSON格式的Post请求


 String httpUrl = HttpRequestUtils.getHttpUrl("http", "127.0.0.1", 9010, "/ar/getAchlistPage");
            String body = HttpRequestUtils.postByJson(restTemplate, httpUrl, null, JSONObject.toJSONString(分页实体参数));
            return JSONObject.parseObject(body, Result.class);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值