RestTemplate是Spring提供的用于发送HTTP请求的客户端工具,它遵循Restful原则,RestTemplate默认依赖JDK的Http连接工具HttpUrlConnection,你也可以替换不同的源,比如OkHttp、Apache HttpComponents等
配置
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class Config {
@Bean
@LoadBalanced
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
}
发送JSON请求
String url = "https://xxx";
// 请求数据
JSONObject json = new JSONObject();
json.put("content", content);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<String> formEntity = new HttpEntity<>(json.toString(), headers);
// 返回数据为JSON字符串
String sdResponse = restTemplate.postForEntity(url, formEntity, String.class).getBody();