티스토리 뷰

WEB 전체/JAVA

Spring RestTemplate 관련

minov 2019. 2. 11. 17:15

차이점 설명

RestTemplate: exchange() vs postForEntity() vs execute()

참조 : https://stackoverflow.com/questions/52364187/resttemplate-exchange-vs-postforentity-vs-execute


각 기능별 예시및 설명

참조 : https://stackoverflow.com/questions/10358345/making-authenticated-post-requests-with-spring-resttemplate-for-android

참조 : https://stackoverflow.com/questions/4075991/post-request-via-resttemplate-in-json/27106518

참조 : https://stackoverflow.com/questions/19238715/how-to-set-an-accept-header-on-spring-resttemplate-request



ex)

@Configuration
public class RestTemplateConfig {

	@Value("${rest.readTimeout:5000}")
	private int readTimeout;

	@Value("${rest.connectTimeout:3000}")
	private int connectTimeout;

	@Bean
	public RestTemplate restClient() {
		HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
		factory.setReadTimeout(readTimeout);
		factory.setConnectTimeout(connectTimeout);

		HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(100).setMaxConnPerRoute(5).build();
		factory.setHttpClient(httpClient);
		return new RestTemplate(factory);
	}

}

public httpPost() throws Exception {
	try {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		if(!StringUtils.isAllEmpty(params)) {
			headers.set("Authorization", "Bearer "+"token String");
		}
		HttpEntity entity = new HttpEntity(bodyJson, headers);
		returnData = restTemplate.restClient().postForObject(String targetUrl, entity, String.class);
			
	} catch (Exception ex) {
		throw HttpServiceException.HTTP_IO_ERROR;
	} 
}


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함