天天看點

RestTemplate使用實戰-exchange方法講解-HTTP請求

@Component
public class HttpUtil {
 
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
 
    @Resource
    private RestTemplate restTemplate;
 
    private static HttpUtil httpUtil;
 
    @PostConstruct
    public void init(){
        httpUtil = this;
        httpUtil.restTemplate = this.restTemplate;
    }
 
    public static <T> String httpRequest(String url, HttpMethod method, HttpEntity<T> entity){
        try {
            //發起一個POST請求
            ResponseEntity<String> result = httpUtil.restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
           return result.getBody();
        } catch (Exception e) {
            logger.error("請求失敗: " + e.getMessage());
        }
        return null;
    }
 
}
           

繼續閱讀