OkHttp是Android发送http请求的常用方式之一,是著名Square公司开发的功能强大的开源网络通信库,深受Android开发者的喜爱,其使用比HttpURLConnection更为简单,而且功能较后者有过之而无不及。所以懂得使用OkHttp是一名优秀的Android开发者必须掌握的。以下的例子是通过OkHttp向服务端请求获取百度主页的html数据。
效果图:
一、设计main_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent