MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private Map<String,List<Cookie>> cookies = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
@Override
public void run() {
super.run();
cookieTest();
}
}.start();
}
public void cookieTest() {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cookieJar(new CookieJar() {
@Override
public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {
cookies.put(httpUrl.host(),list);
}
@NotNull
@Override
public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
List<Cookie> cookies = MainActivity.this.cookies.get(httpUrl.host());
return cookies == null ? new ArrayList<>() : cookies;
}
})
.build();
FormBody formBody = new FormBody.Builder().add("username", "用户名")
.add("password", "密码").build();
Request request = new Request.Builder().url("https://www.wanandroid.com/user/login")
.post(formBody).build();
Call call = okHttpClient.newCall(request);
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();
call = okHttpClient.newCall(request);
try{
Response response = call.execute();
System.out.println(response.body().string());
}catch (IOException e) {
e.printStackTrace();
}
}
}
AndroidManiFest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>//网络请求权限
build.gradle
implementation 'com.squareup.okhttp3:okhttp:4.2.2'//引入OkHttp的依赖
|