0%

RestTemplate请求PUT/DELETE方法无返回值问题

使用exchange

import com.alibaba.fastjson.JSON;
import com.crd.service.routing.bean.AddrInfo;
import com.crd.service.routing.bean.Response;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.*;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;

/**
 * @Author: wzy
 * @Time: Created on 2018/4/27 16:04
 * @Project: sg-imq-console
 * @Modified By: 使用exchange发送put,delete,解决resttemplate无返回值问题
 */
public class RestClientUtil {
    /**
     * 发送/获取 服务端数据(主要用于解决发送put,delete方法无返回值问题).
     *
     * @param url    绝对地址
     * @param method 请求方式
     * @param <T>    返回类型
     * @return 返回结果(响应体)
     */
    public static <T> T exchange(String url, HttpMethod method, Class<T> response, String request) {
        // 请求头
        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);
        // 发送请求
        HttpEntity<String> entity = new HttpEntity<>(request, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> resultEntity = restTemplate.exchange(url, method, entity, response);
        return resultEntity.getBody();
    }

    public static void main(String[] args) {
        String url = "http://127.0.0.1:8088/route/addr/安徽";
        AddrInfo addrInfo = new AddrInfo("安徽", "127.0.0.1:9877");
//        Response response = RestClientUtil.exchange(url,HttpMethod.PUT,Response.class,
//                JSON.toJSONString(addrInfo));
        Response response = RestClientUtil.exchange(url, HttpMethod.DELETE, Response.class,
                null);
        System.out.println(response);
//        RestTemplate restTemplate = new RestTemplate();
//        restTemplate.put(url, addrInfo);
    }
}