Java对接chatgpt进行聊天问答接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | public static void chatgpt() throws IOException { // ChatGPT API endpoint String apiUrl = "https://api.openai.com/v1/chat/completions" ; // Your API key String apiKey = "API_KEY" ; // Request payload (max_tokens越大,回答内容越长,其它参数也是必须的) String payload = "{\"model\": \"gpt-3.5-turbo\",\"messages\": [{\"role\": \"user\", \"content\": \"Can you tell me a small story?\"}], \"max_tokens\": 1500}" ; // Create connection URL url = new URL(apiUrl); HttpURLConnection connection; // Proxy configuration (if using a proxy) String proxyHost = "127.0.0.1" ; int proxyPort = 7890 ; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); connection = (HttpURLConnection) url.openConnection(proxy); // Set connection properties connection.setRequestMethod( "POST" ); connection.setRequestProperty( "Content-Type" , "application/json" ); connection.setRequestProperty( "Authorization" , "Bearer " + apiKey); connection.setDoOutput( true ); // Set connection and read timeouts (in milliseconds) 回答的内容越长,读取的时间越长 int connectionTimeout = 50000 ; // 50 seconds int readTimeout = 50000 ; // 50 seconds connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); // Send request DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(payload); outputStream.flush(); outputStream.close(); // Check response code int responseCode = connection.getResponseCode(); URL url1 = connection.getURL(); String responseMessage = connection.getResponseMessage(); if (responseCode == HttpURLConnection.HTTP_OK) { // Get response BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null ) { response.append(line); } reader.close(); System.out.println( "响应数据:" ); // Process response System.out.println(response.toString()); } else { // Handle error response System.out.println( "Error response code: " + responseCode); System.out.println( "Error response url: " + url1); System.out.println( "Error response responseMessage: " + responseMessage); } } |
打印结果:
响应数据:
{"id":"chatcmpl-7HT72eFZbl3DRwopnE40KqJlMNu4w","object":"chat.completion","created":1684397840,"model":"gpt-3.5-turbo-0301","usage":{"prompt_tokens":20,"completion_tokens":9,"total_tokens":29},"choices":[{"message":{"role":"assistant","content":"Sure, what would you like to know?"},"finish_reason":"stop","index":0}]}
注意:如果遇到400错误,请查看你的参数是否正确;如果read timeout 就是内容太长,需要将超时时间设置大些
前提是:本地已经打开梯子(FQ工具)了,毕竟是外接口
踩过这个坑,还有下一个坑等着你,这一路就是给自己填坑,坑填多了,也就习惯了,直到这一路平坦了,也就无怨无悔了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)