java调用第三方接口获取数据
时间: 2023-09-21 07:06:02 浏览: 91
Java调用第三方接口示范的实现
Java可以使用多种方式调用第三方接口获取数据,其中常用的方式是使用HttpURLConnection或HttpClient类库进行网络请求。
使用HttpURLConnection发送HTTP请求:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpUrlConnectionDemo {
public static void main(String[] args) {
try {
URL url = new URL("https://api.example.com/data");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
System.out.println(content.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
使用HttpClient发送HTTP请求:
```java
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientDemo {
public static void main(String[] args) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://api.example.com/data");
String responseBody = httpClient.execute(httpGet, response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
return EntityUtils.toString(response.getEntity());
} else {
throw new Exception("Unexpected response status: " + status);
}
});
System.out.println(responseBody);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上示例代码仅供参考,实际使用时需要根据接口文档和具体需求进行调整。
阅读全文