java利用jdk11和jdk15新特性零依赖优雅调用GPT-4o,附golang实现对比

这里是小奏 ,觉得文章不错可以关注公众号小奏技术

背景

目前GPT-4o官方不支持所有使用,所以各路大神各显神通

因为只对前端进行了限制。

所以有利用油猴脚本跳过

有自己调用接口的

如果要使用java来实现http调用,放在低版本的jdk

实现起来非常麻烦,主要有几点

  1. 原生的http api非常难用
  2. 不支持模板字符串,所以写json会非常丑陋

所以java 0依赖如何优雅实现GPT-4o的调用呢?还是挺有意思的

jdk17来帮忙

本次我们使用的jdk版本是17

主要用到的特性有两个

  1. jdk15的模板字符串
  2. jdk11的新HttpClient api

话不多说,直接看代码

整体来看是不是很简单优雅

源码如下

java 复制代码
public static void main(String[] args) {
        String openaiApiKey = System.getenv("OPENAI_API_KEY");
        //文本块 需要jdk15+才支持
        String body = """
            {
                "model": "gpt-4o",
                "messages":
                 [
                    {
                        "role": "user",
                        "content": "hello world"
                    }
                ]
            }
            """;
        // jdk11+
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.openai.com/v1/chat/completions"))
            .header("Content-Type", "application/json")
            .header("Authorization", "Bearer " + openaiApiKey)
            .POST(HttpRequest.BodyPublishers.ofString(body)).build();

        HttpClient client = HttpClient.newHttpClient();
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println(response.body());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

goalng实现

golang 复制代码
func main() {
	openaiApiKey := os.Getenv("OPENAI_API_KEY")

	body := map[string]interface{}{
		"model": "gpt-4o",
		"messages": []map[string]string{
			{
				"role":    "user",
				"content": "hello world",
			},
		},
	}

	bodyBytes, err := json.Marshal(body)
	if err != nil {
		fmt.Println("Error marshalling JSON:", err)
		return
	}

	req, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewBuffer(bodyBytes))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+openaiApiKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {

		}
	}(resp.Body)

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}
	fmt.Println(string(respBody))
}

这么看java也挺优雅的哈哈,golang我比较菜,不确定是否有更优雅的实现哈哈

相关推荐
七夜zippoe44 分钟前
仓颉语言核心特性深度解析——现代编程范式的集大成者
开发语言·后端·鸿蒙·鸿蒙系统·仓颉
软件架构师-叶秋1 小时前
spring boot入门篇之开发环境搭建
java·spring boot·后端
QX_hao2 小时前
【Go】--接口(interface)
开发语言·后端·golang
superman超哥2 小时前
仓颉语言中正则表达式引擎的深度剖析与实践
开发语言·后端·仓颉
机器之心2 小时前
单张4090跑到30fps,范浩强团队让VLA实时跑起来了
人工智能·openai
考虑考虑2 小时前
Linux查看系统基本信息
运维·后端·自动化运维
白衣鸽子2 小时前
MapUtils:Java键值操作的瑞士军刀
后端·开源·设计
KoProject3 小时前
发布30款App之后,我总结了这套GLM-4.6全自动化开发流
前端·后端·github
每日一码AI掘金3 小时前
【Spring AI 】Spring AI简介
后端
该用户已不存在3 小时前
构建现代应用的9个Python GUI库
前端·后端·python