请用java写一份调用 文心一言api的 示例代码
时间: 2024-01-23 22:42:16 浏览: 333
java 调用问心一言4.0 API 代码
以下是一个使用Java调用文心一言API的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WenxinYiyanApiDemo {
public static void main(String[] args) {
String apiUrl = "https://v1.hitokoto.cn"; // API地址
String charset = "utf-8"; // 字符集
String responseType = "text/plain"; // 响应类型
try {
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Accept", responseType);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
String line;
StringBuilder responseBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
responseBuilder.append(line);
}
reader.close();
connection.disconnect();
String response = responseBuilder.toString();
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
此代码使用Java的URL和HttpURLConnection类来发送GET请求,并使用BufferedReader类读取响应。在请求的头部中,需要设置Accept-Charset和Accept属性来指定字符集和响应类型。读取响应后,将其转换为字符串并输出。
阅读全文