Spring RestTemplate的使用(解决put,delete方法无返回值问题)

8 篇文章 0 订阅

Spring提供了RestTemplate,可以利用RestTemplate调用REST资源。
同时也可以用作服务端到服务端发送请求。
在Java后台开发中,也可以使用RestTemplate来测试接口。
RestTemplate支持get,put,delete,post操作。

package com.test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.nio.charset.Charset;

/**
 * Created by XFL.
 * time on 2017/3/8 23:37
 * description:测试工具类
 */
public class RestTester {
    private final String url;

    private final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();

    public void set(String key, String value) {
        params.add(key, value);
    }

    /**
     * 构造方法,请求url.
     *
     * @param url 请求地址
     */
    public RestTester(String url) {
        super();
        this.url = url;
    }

    /**
     * 发送get请求.
     *
     * @return 返回请求结果
     */
    public <T> T get(Class<T> cls) {
        String fullUrl = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build().toUriString();
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> resultEntity =  restTemplate.getForEntity(fullUrl, cls);
        return resultEntity.getBody();
    }

    /**
     * 发送post请求.
     *
     * @return 返回请求结果
     */
    public <T> T post(Class<T> cls) {
        String fullUrl = UriComponentsBuilder.fromHttpUrl(url).build().toUriString();
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> resultEntity = restTemplate.postForEntity(fullUrl, params, cls);
        return resultEntity.getBody();
    }

    /**
     * 发送/获取 服务端数据(主要用于解决发送put,delete方法无返回值问题).
     *
     * @param url      绝对地址
     * @param method   请求方式
     * @param bodyType 返回类型
     * @param <T>      返回类型
     * @return 返回结果(响应体)
     */
    public <T> T exchange(String url, HttpMethod method, Class<T> bodyType) {
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
        MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
        // 请求体
        headers.setContentType(mediaType);
        //提供json转化功能
        ObjectMapper mapper = new ObjectMapper();
        String str = null;
        try {
            if (!params.isEmpty()) {
                str = mapper.writeValueAsString(params);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 发送请求
        HttpEntity<String> entity = new HttpEntity<>(str, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> resultEntity = restTemplate.exchange(url, method, entity, bodyType);
        return resultEntity.getBody();
    }
}

测试get方式

package com.test;


/**
 * Created by XFL
 * time on 2017/3/8 23:41
 * description:测试Get方法
 */
public class TestGet {
    public static void main(String[] args) {
        RestTester restTester = new RestTester("http://localhost:8080/Test");
        String result = restTester.get(String.class);
        System.out.println(result);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值