Android Studio中Java代码无法调用ChatGPT API,IntelliJ IDEA可正常运行
Android中调用OpenAI API崩溃的解决办法
问题描述
在IntelliJ IDEA中能正常运行的OpenAI API调用代码,放到Android Studio中运行时,执行到OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());时崩溃退出,控制台仅显示VM连接断开的信息。调用逻辑直接在按钮点击事件(主线程)中执行。
原调用代码
按钮点击事件:
botton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String response= ChatGPTAPIExample.chatGPT("hello, how are you? Can you tell me what's a Fibonacci Number?"); txt.setText(response); } });
OpenAI API调用类
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; public class ChatGPTAPIExample { public static String chatGPT(String prompt) { String url = "https://api.openai.com/v1/chat/completions"; String apiKey = ""; // 需填入有效API Key String model = "gpt-3.5-turbo"; try { URL obj = new URL(url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", "Bearer " + apiKey); connection.setRequestProperty("Content-Type", "application/json"); // 请求体 String body = "{\"model\": \"" + model + "\", \"messages\": [{\"role\": \"user\", \"content\": \"" + prompt + "\"}]}"; connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(body); writer.flush(); writer.close(); // 获取响应 BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuffer response = new StringBuffer(); while ((line = br.readLine()) != null) { response.append(line); } br.close(); return extractMessageFromJSONResponse(response.toString()); } catch (IOException e) { throw new RuntimeException(e); } } public static String extractMessageFromJSONResponse(String response) { int start = response.indexOf("content") + 11; int end = response.indexOf("\"", start); return response.substring(start, end); } }
崩溃原因及解决办法
1. 核心原因:主线程执行网络请求
Android从API Level 11开始,严格禁止在**主线程(UI线程)**中执行网络操作,否则会抛出NetworkOnMainThreadException,直接导致应用崩溃。你的代码在按钮点击事件(主线程)中同步调用网络请求方法,触发了这个限制。
解决办法:将网络请求移到子线程执行
可以用Java线程+Handler快速实现,也可使用Kotlin协程、RxJava等更现代的异步方案。
示例:用线程+Handler修改按钮点击逻辑
botton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 开启子线程执行网络请求 new Thread(new Runnable() { @Override public void run() { String response = null; try { response = ChatGPTAPIExample.chatGPT("hello, how are you? Can you tell me what's a Fibonacci Number?"); } catch (Exception e) { e.printStackTrace(); response = "请求失败:" + e.getMessage(); } final String finalResponse = response; // 回到主线程更新UI runOnUiThread(new Runnable() { @Override public void run() { txt.setText(finalResponse); } }); } }).start(); } });
2. 检查网络权限
确保AndroidManifest.xml中添加了网络权限,没有这个权限应用无法发起网络请求:
<uses-permission android:name="android.permission.INTERNET" />
3. 优化异常处理
原代码直接抛出RuntimeException,会导致异常无法被捕获而崩溃。修改chatGPT()方法的异常处理逻辑,让调用方可控:
public static String chatGPT(String prompt) throws IOException { // ... 原有代码 ... // 移除throw new RuntimeException(e); // 直接抛出IOException,由调用方处理 }
4. 替换脆弱的JSON解析方式
原代码用indexOf截取字符串解析JSON,一旦API返回格式微调就会失败。推荐用JSONObject或Gson库解析:
示例:用JSONObject修改解析方法
import org.json.JSONArray; import org.json.JSONObject; public static String extractMessageFromJSONResponse(String response) throws Exception { JSONObject jsonResponse = new JSONObject(response); JSONArray choices = jsonResponse.getJSONArray("choices"); JSONObject choice = choices.getJSONObject(0); JSONObject message = choice.getJSONObject("message"); return message.getString("content").trim(); }
5. 其他注意事项
- 确保填入的API Key有效,避免因授权失败导致请求错误。
- 若目标SDK>=28(Android 9+),默认禁止明文HTTP请求,但OpenAI API用的是HTTPS,无需额外配置;若测试HTTP接口,需在
AndroidManifest.xml的application标签中添加android:usesCleartextTraffic="true"。
内容的提问来源于stack exchange,提问作者Amir Jalilifard
相关产品推荐
相关产品推荐

