调用chatGPT实现代码机器人(已失效)
最近chatGPT也是非常的火爆,相信大家都看到了,现在提供一种Java调用chatGPT的方法,我们主要通过httpclient来实现!
获取chatGPT登录Token信息
1.需要拥有chatGPT账号,进入官网需要科学上网自行解决!
注册需使用国外手机号!
视频教程:
2.在登录时打开f12,抓取关键包
通过Httpclient实现调用chatGPT
1.在项目中引入Httpclient依赖
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.7</version>
</dependency>
2.测试类
/**
* 使用httpclient调用chatGPT
*/
public class App {
public static void main(String[] args) throws Exception {
//通过登录chatgpt截取页面的token信息
String au = "token";
String sendMsg = "发送的消息";
String user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.42";
String json = "{"action":"next","messages":[{"id":"adfe88e4-f92f-4f21-9145-e227068ce9ca","role":"user","content":{"content_type":"text","parts":[""+sendMsg+""]}}],"parent_message_id":"2a557b41-7e53-4fc4-a28f-cfb0c67b29a7","model":"text-davinci-002-render"}";
System.out.println(json);
HttpPost httpPost = new HttpPost("https://chat.openai.com/backend-api/conversation");
httpPost.addHeader("authorization", au);
httpPost.addHeader("user-agent", user_agent);
httpPost.setHeader("Content-type", "application/json; charset=utf-8");
httpPost.setEntity(new StringEntity(json, StandardCharsets.UTF_8));
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
String body = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
String[] splitR = body.split("
");
String replaceFirst = splitR[splitR.length - 2].replaceFirst("data: ", "");
String res = JSON.parseObject(replaceFirst).getJSONObject("message").getJSONObject("content").getJSONArray("parts").getString(0);
System.out.println(res);
}
}
