Request經常都要攜帶Cookie,上面說過request創建時可以通過header設置參數,Cookie也是參數之一。就像下麵這樣: 然後可以從返回的response里得到新的Cookie,你可能得想辦法把Cookie保存起來。但是OkHttp可以不用我們管理Cookie,自動攜帶,保存和更新 ...
Request經常都要攜帶Cookie,上面說過request創建時可以通過header設置參數,Cookie也是參數之一。就像下麵這樣:
Request request = new Request.Builder() .url(url) .header("Cookie", "xxx") .build();
然後可以從返回的response里得到新的Cookie,你可能得想辦法把Cookie保存起來。
但是OkHttp可以不用我們管理Cookie,自動攜帶,保存和更新Cookie。
方法是在創建OkHttpClient設置管理Cookie的CookieJar
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>(); OkHttpClient okHttpClient = new OkHttpClient.Builder() .cookieJar(new CookieJar() { @Override public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) { cookieStore.put(httpUrl.host(), list); } @Override public List<Cookie> loadForRequest(HttpUrl httpUrl) { List<Cookie> cookies = cookieStore.get(httpUrl.host()); return cookies != null ? cookies : new ArrayList<Cookie>(); } }) .build();
這樣以後發送Request都不用管Cookie這個參數也不用去response獲取新Cookie什麼的了。還能通過cookieStore獲取當前保存的Cookie。
伺服器使用shiro做登錄校驗及許可權驗證的時候,app端訪問時就要帶上cookie,不然請求會提示未登錄
private void postAsynHttp() { mOkHttpClient=new OkHttpClient.Builder() .cookieJar(new CookieJar() { private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>(); @Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { cookieStore.put(url, cookies); cookieStore.put(HttpUrl.parse("http://192.168.31.231:8080/shiro-2"), cookies); for(Cookie cookie:cookies){ System.out.println("cookie Name:"+cookie.name()); System.out.println("cookie Path:"+cookie.path()); } } @Override public List<Cookie> loadForRequest(HttpUrl url) { List<Cookie> cookies = cookieStore.get(HttpUrl.parse("http://192.168.31.231:8080/shiro-2")); if(cookies==null){ System.out.println("沒載入到cookie"); } return cookies != null ? cookies : new ArrayList<Cookie>(); } }) .build(); RequestBody formBody = new FormBody.Builder() .add("username", "admin") .add("password", "admin") .build(); final Request request = new Request.Builder() .url("http://192.168.31.231:8080/shiro-2/shiro-login") .post(formBody) .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String str = response.body().string(); Log.i("wangshu", str); runOnUiThread(new Runnable() { @Override public void run() { showProgress(false); Toast.makeText(getApplicationContext(), "請求成功", Toast.LENGTH_SHORT).show(); } }); } }); }