Android聊天应用中使用HttpURLConnection和AsyncTask进行网络通信
Android聊天应用中使用HttpURLConnection和AsyncTask进行网络通信
之前的代码示例中存在一个错误,使用了InputStreamReader来读取API响应。为了正确读取响应,应该使用BufferedReader。以下代码展示了修正后的ChatRequestTask的doInBackground方法:javaimport 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(); } } } }}
代码解释:
- 使用
BufferedReader读取响应:BufferedReader提供了更高效的读取方式,特别是对于网络流。它可以一次读取多个字符,并将其存储在缓冲区中,从而提高读取效率。2. 构建API请求URL: 使用URLEncoder.encode()对消息进行编码,以确保URL的有效性。3. 发送GET请求: 使用HttpURLConnection发送GET请求到聊天API。4. 解析JSON响应: 使用JSONObject解析API返回的JSON格式的响应数据。5. 显示聊天内容: 将用户输入和聊天机器人的回复添加到聊天界面中。
通过使用BufferedReader和其他网络通信相关的最佳实践,可以构建更健壮、更高效的Android聊天应用程序。
原文地址: https://www.cveoy.top/t/topic/b9JK 著作权归作者所有。请勿转载和采集!