java调用第三方接口
时间: 2023-07-21 21:43:13 浏览: 75
Java调用第三方接口可以使用Java的HTTP客户端库,例如Apache HttpClient、OkHttp、Java原生的HttpURLConnection等。
以下是使用Java原生的HttpURLConnection调用第三方接口的示例代码:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpUrlConnectionExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api/endpoint");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
其中,url为第三方接口的URL地址,可以使用HttpURLConnection的setRequestMethod方法设置请求方法,例如GET、POST等。可以使用BufferedReader读取返回的数据。返回的数据可以存储在一个StringBuffer中,然后使用toString方法转换为字符串输出。
你可以根据具体的需求和第三方接口的要求,设置请求头、请求体、响应码等信息。