java调用第三方接口获取数据
时间: 2023-09-21 21:06:03 浏览: 83
Java调用第三方接口获取数据可以使用Java的HttpURLConnection类或Apache HttpClient库来实现。下面是一个使用HttpURLConnection类的示例代码:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ApiCaller {
public static void main(String[] args) throws Exception {
String apiUrl = "https://api.example.com/data";
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
}
```
这段代码向一个名为apiUrl的接口发送HTTP GET请求,并将响应输出到控制台。你可以根据实际情况修改请求方法,请求头等参数。
阅读全文