Spring Boot调用外部接口的三种方式
在Spring Boot中调用外部API接口,常见的方法有以下三种:
- 使用Spring的RestTemplate
- 使用Java的HttpURLConnection
- 使用Apache的HttpClient
解决方案和示例代码如下:
- 使用Spring的RestTemplate
RestTemplate是Spring提供的用于访问Rest服务的客户端,它提供了多种方法用于访问外部接口。
import org.springframework.web.client.RestTemplate;
public class RestClient {
private RestTemplate restTemplate;
public RestClient(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String get(String url) {
return this.restTemplate.getForObject(url, String.class);
}
public String post(String url, String payload) {
return this.restTemplate.postForObject(url, payload, String.class);
}
}
- 使用Java的HttpURLConnection
HttpURLConnection是Java的标准类,用于处理HTTP请求。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionClient {
public String get(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求类型
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
public String post(String url, String payload) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求类型
con.setRequestMethod("POST");
con.setDoOutput(true);
byte[] outputInBytes = payload.getBytes("UTF-8");
con.getOutputStream().write(outputInBytes);
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
评论已关闭