本文最后更新于1 分钟前,文中所描述的信息可能已发生改变。
java
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
/**
* RestClient工具类
*
**/
@Component
@Slf4j
public class RestUtils
{
private static RestTemplate restTemplate;
@Autowired
public void setRestTemplate(RestTemplate restTemplate)
{
RestUtils.restTemplate = restTemplate;
}
public static String doGet(String targetURL, HttpHeaders httpHeaders) throws IOException
{
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(null, httpHeaders);
final HttpMethod method = HttpMethod.GET;
ResponseEntity<String> responseEntity = restTemplate.exchange(targetURL.trim(), method, entity,
String.class);
return getResponseBody(responseEntity, method, targetURL);
}
public static String doPost(String targetURL, String serialCode) throws IOException
{
ResponseEntity<String> responseEntity = restTemplate.postForEntity(targetURL.trim(), serialCode, String.class);
final HttpMethod method = HttpMethod.POST;
return getResponseBody(responseEntity, method, targetURL);
}
private static String getResponseBody(ResponseEntity<String> entity, HttpMethod method, String targetURL) throws IOException
{
HttpStatus status = entity.getStatusCode();
if (!status.equals(HttpStatus.OK))
{
log.error("{} {} response status is not 200, is {}.", method, targetURL, status);
throw new IOException("response code is not 200.");
}
String responseString = entity.getBody();
if (StringUtils.isBlank(responseString))
{
log.error("{} {} response code 200 but body is null or empty.", method, targetURL);
throw new IOException("response code 200 but body is null or empty.");
}
return responseString;
}
}