我试图在Android中传递一个cookie和一个webview。我尝试使用 CookieManager 和 CookieSyncManager 但无济于事。它不断将我重定向到网站的登录页面。
这是我的代码。
public class RequestSessionState extends AsyncTask<String, Integer, String> {
String cookieString;
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost postCredentials = new HttpPost("https://www.mywebsite.com/users/login?url=users%2Flogin");
List<NameValuePair> credentialsList = new ArrayList<NameValuePair> ();
credentialsList.add(new BasicNameValuePair("data[User][email]",
params[0]));
credentialsList.add(new BasicNameValuePair("data[User][password]",
params[1]));
credentialsList.add(new BasicNameValuePair("_method", "POST"));
try {
postCredentials.setEntity(new UrlEncodedFormEntity(credentialsList));
defaultHttpClient.execute(postCredentials);
CookieSyncManager.createInstance(LoginActivity.this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
SystemClock.sleep(2000);
List<Cookie> cookies = defaultHttpClient.getCookieStore().getCookies();
for (Cookie cookie : cookies) {
cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();
cookieManager.setCookie("https://www.mywebsite.com/path", cookieString);
System.out.println("COOKIE ----------------- " + cookieString);
}
CookieSyncManager.getInstance().sync();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cookieString;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Editor addToSessionState = sessionState.edit();
addToSessionState.putString("cookie", result);
addToSessionState.commit();
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intent);
}
}
这是我下一个活动中的 onCreate:
setContentView(R.layout.activity_home);
consolePageWebView = new WebView(HomeActivity.this);
wvLayout = (RelativeLayout) findViewById(R.id.webViewLayout);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
consolePageWebView.setLayoutParams(params);
wvLayout.addView(consolePageWebView);
sessionState = getSharedPreferences("Session State", Context.MODE_PRIVATE);
String cookieString = sessionState.getString("cookie", null);
WebSettings webSettings = consolePageWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
WebViewClient wvClient = new WebViewClient();
consolePageWebView.setWebViewClient(wvClient);
HashMap<String, String> headerMap = new HashMap<String, String>();
headerMap.put("Cookie", cookieString);
consolePageWebView.loadUrl("https://www.mywebsite.com/path", headerMap);