目录
申请API秘钥
发请求
发请求响应文本
发请求响应图像
访问https://platform.openai.com/
登录后点击右上角的头像,如图:
获取到秘钥后接下来就开始搞代码啦~
添加发请求和解析响应的maven依赖
com.squareup.okhttp3
okhttp
4.10.0
com.fasterxml.jackson.core
jackson-databind
2.13.4
添加一个实体, 用于设置发请求的参数:
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 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 getMessages() {
return messages;
}
public void setMessages(List 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 用于解析 JSON
ObjectMapper objectMapper = new ObjectMapper();
Text text = new Text();
// 设置模型
text.setModel("gpt-3.5-turbo");
// 值越小,生成的文本越可信,但也越无创造性 值越大,生成的文本越有创造性,但也越不可信 范围:0.0-1.0
text.setTemperature(0.7);
text.setMessages(Collections.singletonList(new Text.MessagesBean("user", content)));
// 配置代理
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(HOST, PORT));
// 创建 OkHttpClient
OkHttpClient 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 用于解析 JSON
ObjectMapper 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));
// 创建 OkHttpClient
OkHttpClient 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, 跟我想象的不一样, 可能是我描述不够清晰, 今天就到这啦~
点赞,你的认可是我创作的动力 !
收藏,你的青睐是我努力的方向!
✏️评论,你的意见是我进步的财富!