You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio调用OpenAI API出现org.json.JSONException: No value for choices错误求助

Android Studio调用OpenAI API出现org.json.JSONException: No value for choices错误求助

嗨,我最近在Android Studio里开发一个调用OpenAI API的小应用,结果碰到了这个头疼的JSON解析错误,查了ChatGPT也没搞明白问题根源,来这儿求大家帮忙看看!

我遇到的错误日志如下:

org.json.JSONException: No value for choices
FATAL EXCEPTION: AsyncTask #2
Process: com.example.chatgptapp, PID: 7791
java.lang.RuntimeException: An error occurred while executing doInBackground()
    at android.os.AsyncTask$4.done(AsyncTask.java: 415)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java: 381)
    at java.util.concurrent.FutureTask.setException(FutureTask.java: 250)
    at java.util.concurrent.FutureTask.run(FutureTask.java: 269)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java: 305)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java: 1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java: 644)
    at java.lang.Thread.run(Thread.java: 1012)
Caused by: java.lang.RuntimeException: org.json.JSONException: No value for choices
    at com.example.chatgptapp.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java: 107)
    at com.example.chatgptapp.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java: 65)
    at android.os.AsyncTask$3.call(AsyncTask.java: 394)
    at java.util.concurrent.FutureTask.run(FutureTask.java: 264)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java: 305)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java: 1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java: 644)
    at java.lang.Thread.run(Thread.java: 1012)
Caused by: org.json.JSONException: No value for choices
    at org.json.JSONObject.get(JSONObject.java: 398)
    at org.json.JSONObject.getJSONArray(JSONObject.java: 593)
    at com.example.chatgptapp.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java: 100)
    at com.example.chatgptapp.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java: 65)
    at android.os.AsyncTask$3.call(AsyncTask.java: 394)
    at java.util.concurrent.FutureTask.run(FutureTask.java: 264)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java: 305)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java: 1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java: 644)
    at java.lang.Thread.run(Thread.java: 1012)

以下是项目里的相关代码文件:

app模块的build.gradle.kts:

plugins {
    id("com.android.application")
}

android {
    namespace = "com.example.chatgptapp"
    compileSdk = 34

    defaultConfig {
        applicationId = "com.example.chatgptapp"
        minSdk = 29
        targetSdk = 33
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation("androidx.appcompat:appcompat:1.7.0")
    implementation("com.google.android.material:material:1.12.0")
    implementation("androidx.constraintlayout:constraintlayout:2.2.0")
    testImplementation("junit:junit:4.13.2")
    androidTestImplementation("androidx.test.ext:junit:1.2.1")
    androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1")
    implementation("com.squareup.okhttp3:okhttp:4.9.0")
    implementation("org.json:json:20210307")
}

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ChatGPTApp"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">

        <EditText
            android:id="@+id/editTextUserInput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter your message" />

        <Button
            android:id="@+id/buttonSend"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send"
            android:layout_below="@id/editTextUserInput"
            android:layout_alignParentEnd="true" />

        <TextView
            android:id="@+id/textViewResponse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/buttonSend"
            android:paddingTop="16dp" />
    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java:

package com.example.chatgptapp;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import okhttp3.*;
import org.json.JSONObject;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;

public class MainActivity extends AppCompatActivity {

    private EditText editTextUserInput;
    private Button buttonSend;
    private TextView textViewResponse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextUserInput = findViewById(R.id.editTextUserInput);
        buttonSend = findViewById(R.id.buttonSend);
        textViewResponse = findViewById(R.id.textViewResponse);

        buttonSend.setOnClickListener(view -> {
            String userInput = editTextUserInput.getText().toString();
            callChatGPTAPI(userInput);
        });
    }

    private void callChatGPTAPI(String userInput) {
        String apiKey = "For security, hide my apiKey";
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject json = new JSONObject();
        try {
            json.put("model", "text-davinci-003");
            json.put("prompt", userInput);
            json.put("max_tokens", 100);

            RequestBody body = RequestBody.create(mediaType, json.toString());
            Request request = new Request.Builder()
                    .url("https://api.openai.com/v1/completions")
                    .post(body)
                    .addHeader("Authorization", "Bearer " + apiKey)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(() -> textViewResponse.setText("Error: " + e.getMessage()));
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        runOnUiThread(() -> textViewResponse.setText("Error: " + response.message()));
                        return;
                    }

                    String responseData = response.body().string();
                    Log.d("API Response", responseData);
                    try {
                        JSONObject jsonResponse = new JSONObject(responseData);
                        JSONArray choices = jsonResponse.getJSONArray("choices");
                        String result = choices.getJSONObject(0).getString("text");
                        runOnUiThread(() -> textViewResponse.setText(result));
                    } catch (JSONException e) {
                        runOnUiThread(() -> textViewResponse.setText("JSON Error: " + e.getMessage()));
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            runOnUiThread(() -> textViewResponse.setText("JSON Build Error: " + e.getMessage()));
            e.printStackTrace();
        }
    }
}

备注:内容来源于stack exchange,提问作者ittetsu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 17:32:57