以下是使用 QingYunKe API 实现简单聊天功能的 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 = new String(jsonObject.getString('content').getBytes('ISO-8859-1'), 'UTF-8');
                    // 添加机器人的回复到对话布局
                    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();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    // 显示错误提示
                    Toast.makeText(ChatActivity.this, 'Failed to decode response', Toast.LENGTH_SHORT).show();
                }
            } else {
                // 显示错误提示
                Toast.makeText(ChatActivity.this, 'Failed to get response', Toast.LENGTH_SHORT).show();
            }
        }
    }
}

代码说明:

  1. 使用 EditText 接收用户输入的文字消息。
  2. 使用 LinearLayout 作为聊天记录的容器。
  3. 使用 ProgressBar 显示加载状态。
  4. 使用 AsyncTask 发送网络请求给 QingYunKe API,并解析 JSON 响应。
  5. 将用户和机器人的消息添加到聊天记录布局中。

代码中还包含了对 API 响应的错误处理,以确保程序的稳定运行。

本示例代码展示了如何在 Android 应用中使用 QingYunKe API 实现简单的聊天功能。你可以根据自己的需求对代码进行修改和扩展。例如,你可以添加更多功能,例如语音输入、图片发送等。

注意:

  • 本示例代码使用了 QingYunKe API,需要申请 API Key 和 AppID 才能使用。
  • 你需要在 strings.xml 文件中定义 activity_chat 布局文件,并在布局文件中添加 EditText, LinearLayoutProgressBar 控件。
  • 你需要将代码中的 http://api.qingyunke.com/api.php 替换为你申请的 QingYunKe API 的地址。
  • 你需要将代码中的 free 替换为你申请的 QingYunKe API 的 Key。
  • 你需要将代码中的 0 替换为你申请的 QingYunKe API 的 AppID。

希望本示例代码对你有所帮助。

相关链接:

  • QingYunKe API:https://www.qingyunke.com/doc/api
  • Android 开发文档:https://developer.android.com/
Android 聊天应用:使用 QingYunKe API 实现简单聊天功能

原文地址: http://www.cveoy.top/t/topic/cFeL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录