User Tools

Site Tools


java-example:rest-call

对restTemplate的封装类

package com.xiaosq.common;
 
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
 
/**
 * @author Morgan.L
 * @version 1.0
 * @date 2021/7/18 21:14
 */
@Slf4j
public class RestUtil {
 
  private static Gson gson = new Gson();
 
  public static <T> T doGet(RestTemplate restTemplate, HttpHeaders headers, String url,
      Class<T> responseType) {
    log.info("RestRequest: url={}", url);
 
    T resp;
    if (headers != null) {
      HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
      ResponseEntity<T> respEntity = restTemplate
          .exchange(url, HttpMethod.GET, requestEntity, responseType);
      resp = respEntity.getBody();
    } else {
      resp = restTemplate.getForObject(url, responseType);
    }
    log.info("RestResponse: {}", resp);
    return resp;
  }
 
  public static <T> T doPost(HttpHeaders headers, RestTemplate restTemplate,
      Object form, String url, Class<T> responseType) {
    String dataStr;
    if (form instanceof String) {
      dataStr = (String) form;
    } else {
      dataStr = gson.toJson(form);
    }
 
    log.info("RestRequest: url={}, dataStr={}", url, dataStr);
    HttpEntity<String> httpEntity = new HttpEntity<>(dataStr, headers);
    T resp = restTemplate.postForObject(url, httpEntity, responseType);
    log.info("RestResponse: {}", resp);
    return resp;
  }
}
java-example/rest-call.txt · Last modified: 2021/07/29 08:50 by 127.0.0.1

Except where otherwise noted, content on this wiki is licensed under the following license: 沪ICP备12046235号-2
Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki