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);中设置

时间: 2024-08-02 05:02:42

Android(安卓)WebView设置cookie的相关文章

关于android webview 设置cookie的问题

转自:http://blog.csdn.net/encienqi/article/details/7912733 我们在android中访问网络经常会用到Apache的HttpClient,用此类去访问网络获取数据, 但是在写android界面的时候又时不时的会用到一些WebView组件,这时候访问一个以经登录的页面的时候cookie设置就有个问题 在HttpClient中保存下来的Cookie怎么设置到WebView组件里,让WebView也保持住Cookie状态,也就是登录状态呢? Cook

【Android】WebView设置背景色

Android WebView 设置背景色为透明色 在网上找了 好多的方法都试过了 都不行 1.直接设置成background 为透明色 或者透明图片 (无效) android:background="@android :color/transparent" 2.设置加载的html为透明背景图片(无效) String mobileDetails = "<html xmlns=\"http://www.w3.org/1999/xhtml\">&l

iOS webView 设置cookie

在 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType中添加代码 NSDictionary *dic = @{@"UserToken":[WCAppGlobal defaulAppGlobal].isLogin ? [self _getToken] : @

android安卓动态设置控件宽高

LayoutParams layoutParams=imageView.getLayoutParams(); layoutParams.width=100; layoutParams.height=200; imageView.setLayoutParams(layoutParams);

安卓 logcat设置 Android logcat Settings

安卓 logcat设置 Android logcat Settings 作者:韩梦飞沙 Author:han_meng_fei_sha 邮箱:[email protected] E-mail: 313134555 @qq.com

Android开发--------------WebView(二)之WebView的滑动底部顶部监听,加载进度条等设置

整理一下WebView的一些常用设置,滑动监听,让跳转的页面也在WebView里显示,加载进度,获得标题等等 一,滑动监听 滑动监听的话是需要在WebView基础之上在加强一下,因为在WebView没有直接监听滑动的方法,看WebView的源码则会发现有一个 protected void onScrollChanged(int l, int t, int oldl, int oldt) : 这个方法.是受到保护的所以我们无法直接使用,所以我们写一个加强的WebView,利用接口回调. Scrol

【转】android webview设置内容的字体大小

Enum for specifying the text size. SMALLEST is 50% SMALLER is 75% NORMAL is 100% LARGER is 150% LARGEST is 200%原文:http://www.cnblogs.com/yourancao520/archive/2012/06/14/2548900.html /**  * webview  */ WebView wv; /**  * Manages settings state for a W

android使用webview上传文件(支持相册和拍照),支持最高6.0安卓系统(改进版)

首先学习 http://blog.csdn.net/woshinia/article/details/19030437 对input file的支持 1.注意 mUploadMessage.onReceiveValue(Uri.parse("")); 必须得到调用,无论用户是否选了图,否则会出现再点击不响应的情况 2.上面的参考由于比较老,不适用于安卓5.0系统,因为谷歌5.0以后对webkit做了改动, 相关API发生了变化,那么5.0的需要参考http://blog.csdn.ne

安卓webview和js+html交互利用的addJavascriptInterface和webview.loadUrl(&quot;javascript:**&quot;);

近期做一个项目需要把一个 服务支持的界面用webview来显示..呀 html白雪了js更是一样啥也不会,相信很多初学屌丝员跟我一样,, html开发工具都不知道怎么写..哈哈哈.....现在把做完的结果分享一下先上图了 ,, 这是从项目中特意分离出来的demo这里之上一些关键代码 源码下载地址  http://download.csdn.net/download/yung7086/7554309 步骤 首先在assets目录下建一个html文件 <!DOCTYPE html PUBLIC &quo