java调用chatGPT代码(支持代理)
以下是一段使用 Java 调用 OpenAI 的 GPT-3 的代码示例:
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.InetSocketAddress;import java.net.Proxy;import java.net.URL;import java.nio.charset.StandardCharsets;import javax.net.ssl.HttpsURLConnection; public class ChatGPTExample { public static void main(String[] args) throws IOException { BufferedReader reader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter your question: "); String question = reader.readLine(); // Replace the API key with your own key String apiKey = "your_api_key"; String prompt = question; String endpoint = "https://api.openai.com/v1/engines/davinci/jobs"; URL url = new URL(endpoint); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy_host", proxy_port)); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(proxy); con.setRequestMethod("POST"); con.setRequestProperty("Authorization", "Bearer " + apiKey); con.setRequestProperty("Content-Type", "application/json"); con.setDoOutput(true); String jsonInputString = "{%"prompt%": %"" + prompt + "%"}"; try(OutputStream os = con.getOutputStream()) { byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); } int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); StringBuilder response = new StringBuilder(); String responseLine = null; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } System.out.println("Response: " + response.toString()); } else { System.out.println("Response code: " + responseCode); } } }
请注意,在使用该代码前,需要替换 API 密钥(apiKey)和代理服务器的地址和端口(proxy_host 和 proxy_port)。