Android聊天应用代码示例:使用QingYunKe API实现简单对话

本示例展示了如何使用Android开发一个简单的聊天应用,并利用QingYunKe API实现与用户的对话。代码包含了发送消息、接收回复、处理API响应等关键步骤,并使用AsyncTask进行异步网络请求。

代码示例:

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class ChatActivity extends AppCompatActivity {

    private LinearLayout chatLayout;
    private EditText inputEditText;

    private List<String> chatList;

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

        chatLayout = findViewById(R.id.chatLayout);
        inputEditText = findViewById(R.id.inputEditText);

        chatList = new ArrayList<>();
    }

    public void onSendClick(View view) {
        String message = inputEditText.getText().toString().trim();
        if (!message.isEmpty()) {
            addMessage('You: ' + message);
            inputEditText.setText('');

            // 异步发送请求给API,并处理响应
            new ChatRequestTask().execute(message);
        }
    }

    private void addMessage(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) {
            if (response != null) {
                try {
                    // 解析API响应
                    JSONObject jsonObject = new JSONObject(response);
                    String reply = jsonObject.getString('content');
                    addMessage('Bot: ' + reply);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

代码说明:

  1. 创建聊天界面:使用LinearLayout布局,包含一个用于显示聊天内容的TextView和一个用于输入消息的EditText。
  2. 发送消息:当用户点击发送按钮时,获取输入框内容,并使用addMessage()方法将其显示在聊天区域。
  3. 异步请求API:使用AsyncTask发送GET请求到QingYunKe API,并获取回复内容。
  4. 解析API响应:使用JSONObject解析API返回的JSON数据,获取回复内容,并使用addMessage()方法将其显示在聊天区域。

注意事项:

  1. 需要在项目中添加org.json库的依赖。
  2. 需要在strings.xml文件中定义聊天界面的布局文件。
  3. 需要注册QingYunKe API的开发者账号,并获取API Key。

参考文档:

版权声明:

本示例代码仅供学习参考,禁止用于商业用途。如需商业使用,请咨询相关法律法规。

Android聊天应用代码示例:使用QingYunKe API实现简单对话

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

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