Discuz! BBS

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 74|回复: 1

用okhttp3 实现 curl 访问openAPI

[复制链接]

319

主题

458

帖子

2862

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2862
发表于 7 天前 | 显示全部楼层 |阅读模式
请把以下命令改写成 okhttp3.OkHttpClient 发送的内容: curl https://api.openai.com/v1/completions -H "Authorization: Bearer $OPENAI_API_KEY" -H "Content-Type: application/json" -d '{ "model": "text-davinci-003", "prompt": "Tell me about OpenAI", "max_tokens": 50, "temperature": 0.7 }'
  1. fun sendOpenAIRequest(apiKey: String): String? {
  2.     val client = OkHttpClient()
  3.     val jsonMediaType = "application/json; charset=utf-8".toMediaType()
  4.     val jsonBody = """{
  5.         "model": "text-davinci-003",
  6.         "prompt": "Tell me about OpenAI",
  7.         "max_tokens": 50,
  8.         "temperature": 0.7
  9.     }""".trimIndent()
  10.    
  11.     val body = jsonBody.toRequestBody(jsonMediaType)
  12.     val request = Request.Builder()
  13.         .url("https://api.openai.com/v1/completions")
  14.         .addHeader("Authorization", "Bearer $apiKey")
  15.         .addHeader("Content-Type", "application/json")
  16.         .post(body)
  17.         .build()
  18.    
  19.     var responseString: String? = null
  20.     try {
  21.         val response = client.newCall(request).execute()
  22.         if (response.isSuccessful) {
  23.             responseString = response.body?.string()
  24.             if (responseString.isNullOrEmpty()) {
  25.                 Log.e(TAG, "sendOpenAIRequest: 空数据")
  26.             } else {
  27.                 Log.d(TAG, "sendOpenAIRequest: $responseString")
  28.             }
  29.         } else {
  30.             Log.e(TAG, "Request failed with code: ${response.code}")
  31.         }
  32.     } catch (e: IOException) {
  33.         Log.e(TAG, "IO Exception: ${e.message}", e)
  34.     } catch (e: Exception) {
  35.         Log.e(TAG, "Exception: ${e.message}", e)
  36.     }
  37.     return responseString
  38. }
复制代码
主要改动包括:
1、将 GET 请求改为 POST 请求(使用 .post(body))
2、添加了请求体(request body),包含模型参数
3、添加了必要的请求头:
Authorization: Bearer $apiKey
Content-Type: application/json
4、请求 URL 设置为 https://api.openai.com/v1/completions
这个实现保持了原始 fetchDataSynchronously 方法的错误处理逻辑和日志记录方式。
回复

使用道具 举报

319

主题

458

帖子

2862

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2862
 楼主| 发表于 4 天前 | 显示全部楼层
curl --location --request POST 'http://localhost:11434/api/generate'
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|DiscuzX

GMT+8, 2025-8-1 06:37 , Processed in 0.012458 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表