基於spring boot調用接口的工具類

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.web.client.RestTemplate;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * Rest客戶端
 * 
 * @author heaven
 *
 */
@Builder
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class RestClient {

	/**
	 * 請求方法
	 */
	HttpMethod httpMethod;

	@Builder.Default
	RestTemplate restTemplate = new RestTemplate();
	
	public void setCharsets() {
	    List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
	    for (HttpMessageConverter<?> httpMessageConverter : list) {
	        if(httpMessageConverter instanceof StringHttpMessageConverter) {
	            ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(StandardCharsets.UTF_8);
	        }
	    }
	}

	/**
	 * 發起rest請求
	 * @param url 請求地址
	 * @param body 請求體,對post,put,delete等有請求體有效,對get無效
	 * @param responseType 設置相應結果綁定對象
	 * @param uriVariables 請求變量,用於組裝請求url
	 * @return 響應結果
	 */
	public <T> Optional<T> restRequest(String url, @Nullable Object body, Class<T> responseType,
			Map<String, ?> uriVariables) {
		T response = null;
		switch (httpMethod) {
		case GET:
			response = restTemplate.getForObject(url, responseType, uriVariables);break;
		case POST:
			response = restTemplate.postForObject(url, body, responseType, uriVariables);break;
		default:
			log.error("not support method");
		}
		return Optional.ofNullable(response);
	}

	public String restRequest(String url, String request) {
		
		String result = null;
		/**
		 * 添加headers
		 * 全部請求必須攜帶
		 * */
		HttpHeaders requestHeaders = new HttpHeaders();
		requestHeaders.add("須要攜帶的頭文件", "不須要,能夠不寫");
		HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
		
		if("post".equals(request)) {
			result = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class).getBody();
		}
		if("get".equals(request)) {
			result = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class).getBody();
		}
		return result;
	}
}
相關文章
相關標籤/搜索