|
请把以下命令改写成 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 }'
- fun sendOpenAIRequest(apiKey: String): String? {
- val client = OkHttpClient()
- val jsonMediaType = "application/json; charset=utf-8".toMediaType()
- val jsonBody = """{
- "model": "text-davinci-003",
- "prompt": "Tell me about OpenAI",
- "max_tokens": 50,
- "temperature": 0.7
- }""".trimIndent()
-
- val body = jsonBody.toRequestBody(jsonMediaType)
- val request = Request.Builder()
- .url("https://api.openai.com/v1/completions")
- .addHeader("Authorization", "Bearer $apiKey")
- .addHeader("Content-Type", "application/json")
- .post(body)
- .build()
-
- var responseString: String? = null
- try {
- val response = client.newCall(request).execute()
- if (response.isSuccessful) {
- responseString = response.body?.string()
- if (responseString.isNullOrEmpty()) {
- Log.e(TAG, "sendOpenAIRequest: 空数据")
- } else {
- Log.d(TAG, "sendOpenAIRequest: $responseString")
- }
- } else {
- Log.e(TAG, "Request failed with code: ${response.code}")
- }
- } catch (e: IOException) {
- Log.e(TAG, "IO Exception: ${e.message}", e)
- } catch (e: Exception) {
- Log.e(TAG, "Exception: ${e.message}", e)
- }
- return responseString
- }
复制代码 主要改动包括:
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 方法的错误处理逻辑和日志记录方式。
|
|