需要的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* RestTemplate的配置
*/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
service中使用
@Autowired
private RestTemplateConfig restTemplateConfig;
RestTemplate restTemplate = restTemplateConfig.restTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("sourceCode", "");//自定义请求头参数
Map<String,Object> map=new HashMap<>();
map.put("extcode","");
map.put("signature","");
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(map, headers);
ResponseEntity<String> res = restTemplate.postForEntity("url地址", requestEntity, String.class);
JSONObject jsonObject = JSONObject.parseObject(res.getBody());