RestTemplateHelper.java 1.49 KB
package com.yohoufo.user.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.net.URI;
import java.util.Map;

@Component
public class RestTemplateHelper {

    private static Logger log = LoggerFactory.getLogger(RestTemplateHelper.class);

    @Autowired
    RestTemplate restTemplate;


    /**
     * 使用json格式调用post请求
     *
     * @param url
     * @param params
     * @return
     */
    public <T> T postByJson(String url, Object params, Class<T> responseType) throws RuntimeException {
        log.info("call post with url={}, params={}", url, params);

        MultiValueMap<String, String> headers = new LinkedMultiValueMap();
        headers.set("Content-Type", "application/json; charset=UTF-8");
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

        HttpEntity<Object> entity = new HttpEntity<>(params, headers);
        T response = restTemplate.postForObject(url, entity, responseType);
        return response;
    }


}