Java 调用第三方接口示例代码 - HttpURLConnection
以下是一个简单的 Java 调用第三方接口的示例代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ThirdPartyAPI {
public static void main(String[] args) {
try {
String url = 'http://api.example.com/getData?param1=value1¶m2=value2';
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.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());
}
}
}
在这个示例中,我们使用了 Java 的 HttpURLConnection 类来与第三方 API 进行交互。我们首先构建了一个 URL 对象,然后使用它来打开一个 HttpURLConnection 连接。我们设置了请求方法为 GET,并使用 BufferedReader 来读取 API 返回的响应。最后,我们将响应输出到控制台。
请注意,这只是一个简单的示例代码,实际上,您可能需要对请求进行身份验证或设置其他请求头,具体取决于所使用的 API。
原文地址: https://www.cveoy.top/t/topic/j5Sa 著作权归作者所有。请勿转载和采集!