1、首先在启动类中将RestTemplate注入到容器
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
2、类中使用
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
@Resource
private RestTemplate restTemplate;
public void test(){
String url = "http://" + "端口号" + "接口API地址";
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
MultiValueMap<String, JSONObject> map = new LinkedMultiValueMap<>();
JSONObject jsonObject = new JSONObject();
jsonObject.put("type", "spitem");
JSONObject paramObject = new JSONObject();
paramObject.put("param", jsonObject);
//往map中添加需要传的参数信息
map.add("jsonObject", paramObject);
HttpEntity<Object> requestEntity = new HttpEntity<>(map, headers);
ResponseEntity<ResultModel> exchange = restTemplate.exchange(url, HttpMethod.POST, requestEntity, ResultModel.class);
return exchange.getBody();
}