配置config
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
引入配置
@Autowired
public RestTemplate restTemplate;
restTemplate post携带headers Body 传参
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
HttpHeaders headers = new HttpHeaders();
headers.add("content-type", "application/json");
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("userCode", userCode);
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(requestBody, headers);
try {
ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
String body = response.getBody();
} catch (HttpClientErrorException e) {
String responseBodyAsString = e.getResponseBodyAsString();
}