技术联盟

Android(安卓)WebView设置cookie

最近两天一直想用安卓模拟登陆,利用新的WebView显示登陆后可以访问的页面,但是不管怎么访问需要登陆后才能访问的页面,还是跳回到登陆页,后来网上看了下是cookie没有设置,找了半天才到到合适的设置方法:

 

登陆方法:

private Cookie cookie;
	public static  HttpContext localContext;
	public static  List cookies;//此为保存的cookie
	public  String cookieStr;

	// public static Cookie cookie = null; 
	/**
	 * 登陆时保存cookie
	 * @param url
	 * @param data
	 * @return
	 */
	public String login(String url,String data[]){
		HttpClient client = null;
		String html = null;
		try {
			client = new DefaultHttpClient();
			// 创建cookie store的本地实例  
			CookieStore cookieStore = new BasicCookieStore();  
			localContext = new BasicHttpContext();  
			// 绑定定制的cookie store到本地内容中  
			localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); 
			HttpPost post = new HttpPost(url);
			List parameters = new ArrayList();
			parameters.add(new BasicNameValuePair("username", data[0]));
			parameters.add(new BasicNameValuePair("passwd", data[1]));
			parameters.add(new BasicNameValuePair("login", "%B5%C7%A1%A1%C2%BC"));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,"utf-8");
			post.setEntity(entity);
			
			HttpResponse response = client.execute(post,localContext);
			if(response.getStatusLine().getStatusCode() == 200){
				InputStream content = response.getEntity().getContent();
				BufferedReader buffer = new BufferedReader(new InputStreamReader(content,"gbk"));
				String line = null;
				while((line=buffer.readLine())!=null){
					html+=line;
				}
				  cookies = cookieStore.getCookies();
				 System.out.println("cookies.size():"+cookies.size());
				 if (!cookies.isEmpty()) {  
					 for(int i=0;i<cookies.size();i++){ system.out.println("-="" "+cookies.get(i).tostring());="" }="" buffer.close();="" }else{="" system.out.println("utilslogin:"+response.getstatusline().getstatuscode());="" catch="" (exception="" e)="" {="" e.printstacktrace();="" }finally{="" if(client!="null){" client.getconnectionmanager().shutdown();="" return="" html;="" }<="" pre="">

 

Activity中的oncreate()方法:

 

private WebView wvTempShow;
	private String receiveUrl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_temp_web_view);
		wvTempShow = (WebView) findViewById(R.id.wv_tempShow);
		Intent intent = this.getIntent();
		receiveUrl = intent.getStringExtra("openUrl");
		//获得cookie管理者
		CookieManager cookieManager = CookieManager.getInstance();
		//获取登陆时的cookie
		String oldCookie = 
				UtilsLogin.cookies.get(0).getName()+"="+UtilsLogin.cookies.get(0).getValue()+";"+
				UtilsLogin.cookies.get(1).getName()+"="+UtilsLogin.cookies.get(1).getValue()+";" ;
		System.out.println("oldCookie:"+oldCookie);
		cookieManager.setCookie(receiveUrl, oldCookie);
		wvTempShow.getSettings().setDefaultTextEncodingName("gbk");
		wvTempShow.loadUrl(receiveUrl);
		wvTempShow.setWebViewClient(new MyWebViewClient());
	}

	class MyWebViewClient extends WebViewClient{
		
		
		
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			  
		}
		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
		}
	}
 需要注意的是:要看访问的页面需要什么样的cookie字符串可以用以下方法:

 

 

CookieManager cookieManager = CookieManager.getInstance();
			String CookieStr = cookieManager.getCookie("http://bkjw.guet.edu.cn/student/public/menu.asp?menu=mnall.asp");
            System.out.println("TempWebViewonPageFinished = " + CookieStr);

 

然后自己像以上String oldCookie中一样自己拼好,再在cookieManager.setCookie(url,cookieString);中设置

 

Share this:

码字很辛苦,转载请注明来自技术联盟《Android(安卓)WebView设置cookie》

评论