Android(安卓)WebView设置cookie

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


登陆方法:

private Cookie cookie;
	public static  HttpContext localContext;
	<span style="color: rgb(255, 0, 0); "><strong>public static  List<Cookie> cookies;//此为保存的cookie</strong></span>
	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();
			<span style="color: rgb(255, 0, 0); "><strong>// 创建cookie store的本地实例  
			CookieStore cookieStore = new BasicCookieStore();  
			localContext = new BasicHttpContext();  
			// 绑定定制的cookie store到本地内容中  
			localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); </strong></span>
			HttpPost post = new HttpPost(url);
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			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<span style="color: rgb(255, 0, 0); ">,localContext</span>);
			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;
				}
				 <span style="color: rgb(255, 0, 0); "><strong> cookies = cookieStore.getCookies();</strong></span>
				 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;
	}

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");
		<span style="color: rgb(255, 0, 0); "><strong>//获得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()+";" ;</strong></span>
		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);中设置



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。