spring boot 如何调用外部api
时间: 2024-01-30 08:02:06 浏览: 142
Spring Boot可以使用Java的HttpURLConnection或者Apache的HttpClient来调用外部API。
以下是使用HttpClient进行调用的示例代码:
```java
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExternalApiCall {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://example.com/api/data");
HttpResponse response = client.execute(request);
BufferedReader bufReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufReader.readLine()) != null) {
builder.append(line);
builder.append(System.lineSeparator());
}
String result = builder.toString();
System.out.println(result);
}
}
```
以上代码使用HttpClient发送了一个GET请求到"https://example.com/api/data",并将响应输出到控制台。你可以根据实际情况修改URL、HTTP方法和请求参数等。另外,为了代码的可读性和可维护性,你可以将HttpClient的创建过程封装到一个工具类中。
阅读全文