目录
申请API秘钥
发请求
发请求响应文本
发请求响应图像
申请API秘钥
访问https://platform.openai.com/
登录后点击右上角的头像,如图:
获取到秘钥后接下来就开始搞代码啦~
发请求
添加发请求和解析响应的maven依赖
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.10.0</version>
</dependency><!-- 非springboot, 使用以下依赖 -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.5.2</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.5.2</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.5.2</version>
</dependency><!-- springboot, 使用以下依赖 版本号跟你的父项目保持一致-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-json</artifactId>-->
<!-- </dependency>-->
发请求响应文本
添加一个实体, 用于设置发请求的参数:
import java.io.Serializable;
import java.util.List;/*** api请求的参数** @author 提笔忘字的帝国*/
public class Text implements Serializable {private static final long serialVersionUID = 1L;/*** model : gpt-3.5-turbo messages : [{"role":"user","content":"Say this is a test!"}] temperature : 0.7*/private String model;private double temperature;private List<MessagesBean> messages;public String getModel() {return model;}public void setModel(String model) {this.model = model;}public double getTemperature() {return temperature;}public void setTemperature(double temperature) {this.temperature = temperature;}public List<MessagesBean> getMessages() {return messages;}public void setMessages(List<MessagesBean> messages) {this.messages = messages;}public static class MessagesBean implements Serializable {private static final long serialVersionUID = 1L;/*** role : user content : Say this is a test!*/private String role;private String content;public MessagesBean(String user, String content) {this.role = user;this.content = content;}public String getRole() {return role;}public void setRole(String role) {this.role = role;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}}
}
发请求:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Collections;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;import okhttp3.*;/*** @author 提笔忘字的帝国*/
public class Test {/** API秘钥 添加自己的秘钥 */private static final String KEY = "";/** url */private static final String URL = "https://api.openai.com/v1/chat/completions";/** 配置代理服务的ip 根据自己实际情况配置 */private static final String HOST = "127.0.0.1";/** 配置代理服务的端口 根据自己实际情况配置 */private static final int PORT = 7890;public static void main(String[] args) throws JsonProcessingException {// 输入内容String content = "您好";// 创建 ObjectMapper 用于解析 JSONObjectMapper objectMapper = new ObjectMapper();Text text = new Text();// 设置模型text.setModel("gpt-3.5-turbo");// 值越小,生成的文本越可信,但也越无创造性 值越大,生成的文本越有创造性,但也越不可信 范围:0.0-1.0text.setTemperature(0.7);text.setMessages(Collections.singletonList(new Text.MessagesBean("user", content)));// 配置代理Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(HOST, PORT));// 创建 OkHttpClientOkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();// 创建请求体,携带 JSON 参数RequestBody requestBody = RequestBody.create(objectMapper.writeValueAsString(text),MediaType.parse("application/json; charset=utf-8"));// 创建请求Request request =new Request.Builder().url(URL).addHeader("Authorization", "Bearer ".concat(KEY)).post(requestBody).build();// 发送请求并处理响应try (Response response = client.newCall(request).execute()) {if (!response.isSuccessful()) {throw new IOException("Unexpected code " + response);}// 解析json 获取结果JsonNode jsonNode = objectMapper.readTree(response.body().string());System.out.println(jsonNode.get("choices").get(0).get("message").get("content").asText());} catch (IOException e) {e.printStackTrace();}}
}
发请求响应图像
添加一个实体, 用于设置发请求的参数:
import java.io.Serializable;/*** api请求的参数** @author 提笔忘字的帝国*/
public class Images implements Serializable {private static final long serialVersionUID = 1L;/*** prompt : A cute baby sea otter n : 2 size : 1024x1024*/private String prompt;private int n;private String size;public String getPrompt() {return prompt;}public void setPrompt(String prompt) {this.prompt = prompt;}public int getN() {return n;}public void setN(int n) {this.n = n;}public String getSize() {return size;}public void setSize(String size) {this.size = size;}
}
发请求:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;import okhttp3.*;/*** @author 提笔忘字的帝国*/
public class TestImg {/** API秘钥 添加自己的秘钥 */private static final String KEY = "";/** url */private static final String URL = "https://api.openai.com/v1/images/generations";/** 配置代理服务的ip 根据自己实际情况配置 */private static final String HOST = "127.0.0.1";/** 配置代理服务的端口 根据自己实际情况配置 */private static final int PORT = 7890;public static void main(String[] args) throws JsonProcessingException {// 输入内容String content = "生成一只功夫熊猫";// 创建 ObjectMapper 用于解析 JSONObjectMapper objectMapper = new ObjectMapper();Images images = new Images();// 生成图像的描述images.setPrompt(content);// 生成图像的数量images.setN(1);// 生成图像的尺寸images.setSize("1024x1024");// 配置代理Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(HOST, PORT));// 创建 OkHttpClientOkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();// 创建请求体,携带 JSON 参数RequestBody requestBody = RequestBody.create(objectMapper.writeValueAsString(images),MediaType.parse("application/json; charset=utf-8"));// 创建请求Request request =new Request.Builder().url(URL).addHeader("Authorization", "Bearer ".concat(KEY)).post(requestBody).build();// 发送请求并处理响应try (Response response = client.newCall(request).execute()) {if (!response.isSuccessful()) {throw new IOException("Unexpected code " + response);}// 解析json 获取结果JsonNode jsonNode = objectMapper.readTree(response.body().string());System.out.println(jsonNode.get("data").get(0).get("url").asText());} catch (IOException e) {e.printStackTrace();}}
}
可以看到响应回来的是一个图像的链接, 点击查看链接即可, 下图是生成回来的图像
emmmm, 跟我想象的不一样, 可能是我描述不够清晰, 今天就到这啦~
👍点赞,你的认可是我创作的动力 !
🌟收藏,你的青睐是我努力的方向!
✏️评论,你的意见是我进步的财富!