前言
- HttpUrlConnection继承自URLConnection,可用于向指定网站发送GET请求、POST请求,所以在使用上相对简单,并且易于扩展,推荐使用。
- HttpURLconnection是基于http协议的,支持get,post,put,delete等各种请求方式,最常用的就是get和post,下面针对这GET请求方式进行讲解。
一、编写聊天界面
——界面布局解析图及效果图——
1.1 主界面布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<!--展示消息列表RecyclerView-->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rcv_chatMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="8dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="#F8F7F7"
android:gravity="center"
>
<EditText
android:id="@+id/ed_inputChatMessage"
android:layout_width="wrap_content"
android:layout_height="36dp"
android:hint="请输入你要发送的消息"
android:maxLines="5"
android:layout_weight="1"
android:background="@drawable/edit_background"
android:layout_marginLeft="12dp"
/>
<Button
android:id="@+id/btn_sendMessage"
android:layout_width="wrap_content"
android:layout_height="28dp"
android:text="发送"
android:textColor="#fff"
android:textSize="16sp"
android:layout_marginLeft="10dp"
android:layout_marginRight="12dp"
android:background="@drawable/button_background"
/>
</LinearLayout>
</LinearLayout>
1.2 消息适配器子布局代码(通过判断消息类型来动态加载左右消息布局)
左边消息布局
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginRight="50dp"
android:layout_marginTop="15dp"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity<