我们定义了一个名为ChartGPTConfig的类,它有两个私有成员变量apiKey和apiUrl,分别表示ChartGPT的API密钥和API URL。
public class ChartGPTConfig {
private final String apiKey;
private final String apiUrl;
public ChartGPTConfig(String apiKey, String apiUrl) {
this.apiKey = apiKey;
this.apiUrl = apiUrl;
}
public String getApiKey() {
return apiKey;
}
public String getApiUrl() {
return apiUrl;
}
}
简单调用示例:
public class ChartGPTExample {
public static void main(String[] args) {
ChartGPTConfig config = new ChartGPTConfig("YOUR_API_KEY", "https://api.chartgpt.com/v1/generate");
String query = "What is the population of China?";
try {
String response = callChartGPTAPI(config, query);
System.out.println("Response: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
private static String callChartGPTAPI(ChartGPTConfig config, String query) throws IOException {
OkHttpClient client = new OkHttpClient();
String url = config.getApiUrl() + "?query=" + query;
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", "Bearer " + config.getApiKey())
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}
示例中使用了OkHttp库来发送HTTP请求,可以通过Maven或Gradle将依赖添加。
Maven引入OkHttp依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
Gradle引入OkHttp依赖:
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
}