准备工作:
编辑 app/build.gradle文件,在dependencies闭包中添加以下内容:
implementation 'com.squareup.okhttp3:okhttp:4.0.1'
添加上述依赖会自动下载两个库,一个是OkHttp库,一个是Okio库,后者是前者的通信基础。其中4.0.1是我写这篇博客时的最新版本,你可以访问OkHttp的项目主页来查看当前的最新版本是多少,OkHttp的项目主页地址如下:
添加网络权限,在AndroidManifest.xml文件中加入以下代码:
<uses-permission android:name="android.permission.INTERNET" />
我们先来看下程序运行的效果图:
这里就是点击按钮,发送请求,然后显示返回的数据。
MainActivity的xml布局代码如下:
<?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">
<Button
android:id="@+id/btn_send_request"
android:layout_width="match_parent"
android:layout_height