springboot RestTemplate 服务端之间http请求restful服务接口

RestTemplate使spring能够方便的使用rest资源,他定义了许多与rest交互分方法,并且对应大多数http请求方法。这里我使用exchange()方法完成请求。

exchange() 是在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中映射得到的

public class HttpConnectUtil {

    /**
     * @param requestParam  请求时带的实体类,参数等
     * @param url           HTTP 请求地址
     * @param header        请求头,没有请求头的设置为null即可
     * @param requestMethod 请求方法 GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
     * @return 返回的是Object类型 其中ResponseEntity.getBody()请求返回json内容;ResponseEntity.getStatusCodeValue() 请求返回http状态码
     */
    public static <T> ResponseEntity tempHttp(T requestParam, String url, String header, String requestMethod) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Authorization", header);
        HttpEntity<T> requestEntity = new HttpEntity<>(requestParam, requestHeaders);
        ResponseEntity response;
        HttpMethod httpMethod;
        String method = requestMethod.toLowerCase();
        switch (method) {
            case "post":
                httpMethod = HttpMethod.POST;
                break;
            case "put":
                httpMethod = HttpMethod.PUT;
                break;
            case "delete":
                httpMethod = HttpMethod.DELETE;
                break;
            case "patch":
                httpMethod = HttpMethod.PATCH;
                break;
            case "head":
                httpMethod = HttpMethod.HEAD;
                break;
            case "options":
                httpMethod = HttpMethod.OPTIONS;
                break;
            case "trace":
                httpMethod = HttpMethod.TRACE;
                break;
            default:
                httpMethod = HttpMethod.GET;
        }
        response = restTemplate.exchange(url, httpMethod, requestEntity, String.class);
        return response;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值