1.添加依賴:
implementation("com.squareup.okhttp3:okhttp:4.9.0")
2.配置請求:
- 2.1 GET請求:
- GET 同步請求:
//同步請求,請求時沒回應(yīng)拔疚,會阻塞
public void getSync(View view) {
OkHttpClient okHttpClient = new OkHttpClient();
//網(wǎng)絡(luò)請求必須在子線程執(zhí)行
new Thread(){
@Override
public void run() {
//Request代表請求對象肥隆,會將域名,請求地址稚失,參數(shù)封裝
//若是要在get后面直接加參數(shù)格式是在get后面加:?a=1&b=2
Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();
//準(zhǔn)備好請求的Call對象
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
Log.i(TAG, "getSync: "+response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
- GET異步請求:
public void getAsync(View view) {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();
//準(zhǔn)備好請求的Call對象
Call call = okHttpClient.newCall(request);
//進(jìn)行異步請求
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//響應(yīng)碼 200~299成功栋艳,400~500服務(wù)器錯誤,跟服務(wù)器的通信是成功的都會回調(diào)這個函數(shù)句各,但是服務(wù)器處理請求的數(shù)據(jù)不一定成功
if (response.isSuccessful()){
Log.i(TAG, "getAsync: "+response.body().string());
}
}
});
}
- 2.2 POST請求:
- POST同步請求:
public void postSync(View view) {
OkHttpClient okHttpClient = new OkHttpClient();
//okhttp創(chuàng)建的request對象默認(rèn)是get請求吸占,如果是post要使用FormBody配合.post()設(shè)置
//而POST請求要設(shè)置RequestBody
new Thread(){
@Override
public void run() {
FormBody formBody = new FormBody.Builder()
.add("a", "1")
.add("b", "2")
.build();
Request request = new Request.Builder()
.url("https://www.httpbin.org/post")
.post(formBody)
.build();
//準(zhǔn)備好請求的Call對象
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
Log.i(TAG, "PostSync: "+response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
- POST異步請求:
public void postAsync(View view) {
OkHttpClient okHttpClient = new OkHttpClient();
FormBody formBody = new FormBody.Builder()
.add("a", "1")
.add("b", "2")
.build();
Request request = new Request.Builder()
.url("https://www.httpbin.org/post")
.post(formBody)
.build();
//準(zhǔn)備好請求的Call對象
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if (response.isSuccessful()){
Log.i(TAG, "PostAsync: "+response.body().string());
}
}
});
}
兩者綜合來看,request對應(yīng)的是get請求凿宾,而formbody對應(yīng)的是post請求
3.添加攔截器:
public void interceptorTest(){
//addInterceptor一定在前面執(zhí)行矾屯,addNetworkInterceptor一定在后面執(zhí)行
//使用cache緩存
OkHttpClient okHttpClient = new OkHttpClient.Builder()
//開啟緩存
.cache(new Cache(new File("C:\\Users\\Administrator\\Desktop\\cache"),1024*1024))
.addInterceptor(new Interceptor() {
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
//請求之前的前置處理,和請求之后的后置處理
//例如請求前初厚,添加平臺件蚕,版本號
//在請求前可以拿到這個request對象,再重新封裝一個新的request,把平臺信息和版本號封裝進(jìn)去,再發(fā)出去
//攔截器可以添加多個产禾,按照順序來執(zhí)行
Request request = chain.request().newBuilder().addHeader("os", "android").addHeader("version", "1.1.0").build();
Response response = chain.proceed(request);
return response;
}
}).addNetworkInterceptor(new Interceptor() {
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
System.out.println("version:"+chain.request().header("version"));
return chain.proceed(chain.request());
}
}).build();
Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
4.文件上傳:
public void uploadFileTest(){
//上傳的是:文件的key,文件的名字排作,文件本身
//采用的是MultipartBody來封裝
//MediaType詳情參考:https://blog.csdn.net/sinat_34241861/article/details/110648469
//Content_Type:application/x-www-form-urlencoded 默認(rèn)是這種提交,采取的形式是鍵值對形式:key1:value1&key2:value2&key3:value3
//Content_type:multipart/form-data下愈,數(shù)據(jù)被編碼為一條消息纽绍,一般用于文件上傳
//Content_Type:application/octet-stream,提交二進(jìn)制數(shù)據(jù)势似,如果用于文件上傳拌夏,只能上傳一個文件
//Content_Type:application/json,提交json數(shù)據(jù)
OkHttpClient okHttpClient = new OkHttpClient();
File file1 = new File("C:\\Users\\Administrator\\Desktop\\1.txt");
File file2 = new File("C:\\Users\\Administrator\\Desktop\\2.txt");
MultipartBody multipartBody = new MultipartBody.Builder()
.addFormDataPart("file1", file1.getName(), RequestBody.create(file1, MediaType.parse("text/plain")))
.addFormDataPart("file2", file2.getName(), RequestBody.create(file1, MediaType.parse("text/plain")))
.addFormDataPart("a","1")//還可以添加額外的參數(shù)
.build();
Request request = new Request.Builder().url("https://www.httpbin.org/post").post(multipartBody).build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
5.Json數(shù)據(jù)上傳:
//上傳json數(shù)據(jù)
//使用的RequestBody來封裝
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = RequestBody.create("{\"a\":1,\"b\":2}", MediaType.parse("application/json"));
Request request = new Request.Builder().url("https://www.httpbin.org/post").post(requestBody).build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
.使用cookies:
cookie是某些網(wǎng)站為了辨別用戶的身份僧著,進(jìn)行會話跟蹤(比如確定登錄狀態(tài))而存儲在本地終端上的數(shù)據(jù),由客戶端保存信息
public class UseCookie {
//cookie的相關(guān)配置
Map<String,List<Cookie>> cookies = new HashMap<>();
@Test
public void useCookie(){
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cookieJar(new CookieJar() {
@Override
public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {
//會把服務(wù)器返回的cookie封裝成list集合障簿,返回回來盹愚,可以用文件保存或者放在內(nèi)存中
cookies.put(httpUrl.host(),list);
}
@NotNull
@Override
public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
//請求網(wǎng)站的url
List<Cookie> cookies = UseCookie.this.cookies.get(httpUrl.host());
return cookies == null ? new ArrayList<Cookie>():cookies;
}
})
.build();
//填入你自己的wanandroid賬號和密碼
FormBody formBody = new FormBody.Builder().add("username", "xxx")
.add("password", "xxxxxx").build();
Request request = new Request.Builder().url("https://www.wanandroid.com/user/login")
.post(formBody)
.build();
//準(zhǔn)備好請求的Call對象
Call call = okHttpClient.newCall(request);
//進(jìn)行同步請求
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
//請求收藏文章列表接口
request = new Request.Builder().url("https://www.wanandroid.com/lg/collect/list/0/json")
.build();
//準(zhǔn)備好請求的Call對象
call = okHttpClient.newCall(request);
//進(jìn)行同步請求
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}