继续上面的问题,改成java示例
时间: 2023-06-11 10:06:35 浏览: 76
Java例子
好的,以下是一个简单的Java示例,展示如何使用CSDN开发的ChitGPT与用户进行对话:
```java
import java.util.Scanner;
import org.json.JSONObject;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ChitGPTDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("User: ");
String input = scanner.nextLine();
String response = getResponseFromChitGPT(input);
System.out.println("ChitGPT: " + response);
}
}
private static String getResponseFromChitGPT(String input) {
try {
URL url = new URL("https://api.chitgpt.csdn.net/generate/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
String requestBody = "{\"text\":\"" + input + "\"}";
byte[] requestBodyBytes = requestBody.getBytes("utf-8");
con.getOutputStream().write(requestBodyBytes);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject jsonResponse = new JSONObject(response.toString());
String generatedText = jsonResponse.getString("text");
return generatedText;
} catch (Exception e) {
e.printStackTrace();
return "Sorry, an error occurred.";
}
}
}
```
这个示例中,我们使用了Java的URL和HttpURLConnection类来向CSDN开发的ChitGPT API发送POST请求。在发送请求时,我们需要将用户输入的文本作为请求体发送给API,API将会返回生成的文本作为响应。最后,我们将响应返回给用户。
阅读全文