java调用第三方接口代码
以下是一个简单的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/cFgZ 著作权归作者所有。请勿转载和采集!