相关链接:OkHttp官网、Okhttp3基本使用
基本概念
OkHttp 是一个用于网络请求的框架 (类库)。
在Android项目中引入依赖包
GET同步请求
package com.clc.app37;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.util.Log;import java.io.IOException;import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;import static android.content.ContentValues.TAG;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//匿名Thread子类对象new Thread(){@Overridepublic void run() {OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().get()//请求方式;默认就是GET请求,可以不写.url("https://www.baidu.com").build();Call call = client.newCall(request);try {//execute():同步请求,不会自动另开线程;因为不可以在主线程中进行网络访问操作,所以我们自己要另开线程Response response = call.execute();Log.d("------", "run: "+response.body().string().substring(0,100));} catch (IOException e) {e.printStackTrace();}}}.start();}
}
GET异步请求
package com.clc.app37;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.util.Log;import org.jetbrains.annotations.NotNull;import java.io.IOException;import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;public class MainActivity extends AppCompatActivity {private String TAG = "MainActivity------";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().get()//请求方式;默认就是GET请求,可以不写.url("https://www.baidu.com").build();Call call = client.newCall(request);//enqueue():异步请求,会自动另开线程call.enqueue(new Callback() {@Overridepublic void onFailure(@NotNull Call call, @NotNull IOException e) {Log.d(TAG, "onFailure: ");}@Overridepublic void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {Log.d(TAG, "onResponse: "+response.body().string().substring(0,200));}});}
}
请求时需要提交内容,则用POST请求
不同提交内容的POST请求,请参考this blog