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

文章作者: wuzhiyong
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 wuzhiyong !
评论
 上一篇
springboot转发重定向问题 springboot转发重定向问题
浏览器地址显示问题 return "forward:/list"; 浏览器地址不变,是转发源地址; return "redirect:/list"; 浏览器地址变成list地址. document.querySele
2020-11-17
下一篇 
hbase设置ttl hbase设置ttl
Hbase关于TTL ColumnFamilies可以以秒为单位来设置 TTL(Time To Live)长度,一旦达到到期时间,HBase 将自动删除行。 设置 hbase.store.delete.expired.storefile 为
2020-11-12
  目录