Java | 智谱API调用实践
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GaiGeAPI {
public static void main(String[] args) throws Exception {
String apiKey = "您的API密钥";
String url = "https://api.gaige.net/v1/search/images?q=cat&api_key=" + apiKey;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为 "GET"
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
// 读取响应
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());
}
}
这段代码展示了如何使用Java进行智谱API的调用。首先,它创建了一个URL对象,然后通过HttpURLConnection建立连接,设置请求方法为GET,发送请求并获取响应。最后,它读取响应并打印结果。这个过程展示了如何进行API调用,并处理返回的数据。
评论已关闭