一、使用OkHttp的步驟
1、在項目中添加OkHttp庫的依賴
在File->Project Structure->app->Dependencies->+(添加)->搜索OkHttp->找“com.squareup.okhttp3:okhttp:3.8.1”確定添加
2、首先創建OkHttpClient實例
OkHttpClient client = new OkHttpClient();
3、發送GET請求或POST請求
GET請求:創建一個request對象,並在build()前連綴很多方法來豐富這個request對象
Request request = new Request.Builder().url("http://www.baidu.com").build();
POST請求:先構建body對象存放數據,然後在Request.Builder()調用post方法將body對象傳入
RequestBody requestBody = new FormBody.Builder()
.add("username","admin")
.add("password","123456")
.build();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.post(requestBody)
.build();
4、調用execute()方法發送請求並獲取服務器返回的數據
Response response = client.newCall(request).execute();
二、實現一下吧
1、效果圖
效果圖和上一篇HttpURLConnection的使用中的是一樣的,因爲發送都是訪問百度頁面的請求
2、佈局文件
<?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/send_request"
android:layout_width="match_parent"
android:layout_height="80dp"
android:text="發送請求"
android:textSize="25dp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
3、MainActivity.java
public class MainActivity extends AppCompatActivity {
Button sendRequest;
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest = (Button) findViewById(send_request);
sendRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
try{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://www.baidu.com").build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
showResponse(responseData);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
});
}
private void showResponse(final String response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//在這裏進行UI操作,將結果顯示到界面上
responseText.setText(response);
}
});
}
}
4、在清單文件中聲明網絡權限
<uses-permission android:name="android.permission.INTERNET"/>