Android 聊天机器人代码修复:解决"怎么他不回答了"问题
非常抱歉之前的代码有错误,以下是经过修正的代码:
package com.example.pg_helper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class ChatActivity extends AppCompatActivity {
    private EditText inputEditText;
    private LinearLayout chatLayout;
    private ProgressBar progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        inputEditText = findViewById(R.id.inputEditText);
        chatLayout = findViewById(R.id.chatLayout);
        progressBar = findViewById(R.id.progressBar);
    }
    public void onSendClick(View view) {
        String message = inputEditText.getText().toString().trim();
        if (!message.isEmpty()) {
            // 显示加载提示
            progressBar.setVisibility(View.VISIBLE);
            // 添加用户的消息到对话布局
            addMessageToChatLayout('User: ' + message);
            // 异步发送请求给API,并处理响应
            new ChatRequestTask().execute(message);
        } else {
            // 显示错误提示
            Toast.makeText(this, 'Please enter a message', Toast.LENGTH_SHORT).show();
        }
    }
    private void addMessageToChatLayout(String message) {
        TextView textView = new TextView(this);
        textView.setText(message);
        chatLayout.addView(textView);
    }
    private class ChatRequestTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String message = params[0];
            try {
                // 构建API请求URL
                String url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg=' + URLEncoder.encode(message, 'UTF-8');
                // 发送GET请求给API,并获取响应
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setRequestMethod('GET');
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                return response.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(String response) {
            // 隐藏加载提示
            progressBar.setVisibility(View.GONE);
            if (response != null) {
                try {
                    // 解析API响应
                    JSONObject jsonObject = new JSONObject(response);
                    String reply = jsonObject.getString('content');
                    // 添加机器人的回复到对话布局
                    addMessageToChatLayout('Bot: ' + reply);
                    // 清空输入框
                    inputEditText.setText('');
                    // 滚动到最新的聊天记录
                    chatLayout.post(new Runnable() {
                        @Override
                        public void run() {
                            chatLayout.scrollTo(0, chatLayout.getBottom());
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                    // 显示错误提示
                    Toast.makeText(ChatActivity.this, 'Failed to parse response', Toast.LENGTH_SHORT).show();
                }
            } else {
                // 显示错误提示
                Toast.makeText(ChatActivity.this, 'Failed to get response', Toast.LENGTH_SHORT).show();
            }
        }
    }
}
非常抱歉之前的代码有错误,希望这次提供的代码没有问题。如果还有其他问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/cFED 著作权归作者所有。请勿转载和采集!