最近一直在使用玩android開放的API做一個項目,在收藏接口的時候遇到了問題,登陸成功後在點擊收藏還是提示未登錄,然後慢慢接觸到了cookie
此項目的接口數據來源於玩Android
思路:
使用postman模擬請求數據登錄之前我們可以看到Temporary Headers中有一個Cookie字段,現在的值就是默認顯示的內容
當我們登錄成功後cookie字段的內容爲:
可以看到postman幫我們報存了cookie中的內容,這樣當我們進行收藏等操作的時候就可以操作成功,但是android中不會自動將cookie進行報存
直接進入主題:
@FormUrlEncoded
@POST("user/login")//登錄接口數據
fun logintext(@Field("username") username:String,@Field("password") password:String):rx.Observable<Response<LoginBean>>
主活動代碼:
private void onClick(View v) {
final String address = "https://www.wanandroid.com/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(address)//基礎URL 建議以 / 結尾
.addConverterFactory(GsonConverterFactory.create())//設置 Json 轉換器
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())//RxJava 適配器
.build();
API workPlaneService = retrofit.create(API.class);
workPlaneService
.logintext("yuhang66", "123456")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Response<LoginBean>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.i("eraaa", e.toString());
}
@Override
public void onNext(Response<LoginBean> loginBeanResponse) {
Headers headers = loginBeanResponse.headers();//我們通過Response的headers對象獲取到響應頭信息。
List<String> values = headers.values("Set-Cookie");//通過“Set-Cookie”字段獲取到服務器返回的Cookie信息
for (String s : values) {
Log.e("ohmys", s);
}
Log.e("ohmys", "@" + values);//這裏responseBodyResponse.body()獲取的就是ResultBean對象
initText(values);//登錄成功後 發起收藏頁面的請求
}
});
}
private void initText(final List<String> values) {
new Thread(new Runnable() {
@Override
public void run() {
//這是一個查詢產品詳細信息的接口
FormBody contentBody = new FormBody.Builder()
.add("id", "2334")
.build();
//將cookie信息放到請求頭中去
Request contentRequest = new Request.Builder()
.url("https://www.wanandroid.com/lg/collect/1165/json")
.header("Cookie", values.toString())//添加cookie
.post(contentBody)
.build();
okhttp3.Call contentCall = client.httpClient.newCall(contentRequest);
try {
okhttp3.Response contentResponse = contentCall.execute();
String contentResult = contentResponse.body().string();
Log.d("lalala", contentResult);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
這樣就可以收藏成功了
要將cookie進行持久化的話 你可以使用SharedPerference等其他方法進行報存到android中