但使书种多,会有岁稔时。这篇文章主要讲述Android中Http加载如何得到Cookie和 WebView 加载网页如何得到的Cookie相关的知识,希望能为你提供帮助。
最近做项目在手机端登录Http请求和
WebView 记载登录获取Cookie信息,可查看Cookie信息。
如图:
文章图片
Http请求获取Cookie信息:
public static String request(String httpUrl, String params, Context context) { BufferedReader reader = null; String result = null; String httpurl = " http://xwwscs.com"; StringBuffer sbf = new StringBuffer(); try { URL url = new URL(httpurl + "/app.php"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Cookie", CookieUtil.getParam(context).toString()); connection.setConnectTimeout(3000); // 是否输入参数 connection.setDoOutput(true); byte[] bypes = params.toString().getBytes(); connection.getOutputStream().write(bypes); // 输入参数 connection.connect(); InputStream is = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String strRead = null; while ((strRead = reader.readLine()) != null) { sbf.append(strRead); sbf.append("\r\n"); } reader.close(); Map< String, List< String> > cookie_map = connection.getHeaderFields(); List< String> cookies = cookie_map.get("Set-Cookie"); if (null != cookies & & 0 < cookies.size()) { String s = ""; for (String cookie : cookies) { if (s.isEmpty()) { s = cookie; } else { s += "; " + cookie; } } Log.i("cookie", s); } result = sbf.toString(); } catch (Exception e) { result = "error"; e.printStackTrace(); } return result; } }
WebView加载网页获取Cookie
webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub return super.shouldOverrideUrlLoading(view, url); } @Override public void onPageFinished(WebView view, String url) { CookieManager cookieManager = CookieManager.getInstance(); String CookieStr = cookieManager.getCookie(url); if(CookieStr!=null) { Log.i("cookie", CookieStr); } super.onPageFinished(view, url); }});
【Android中Http加载如何得到Cookie和 WebView 加载网页如何得到的Cookie】
推荐阅读
- Android 7.0 ActivityManagerService 进程管理相关流程分析
- rnandroid环境搭建
- Android -- 下载进度条(只要有网址就行)
- Android中实现全屏无标题栏的两种办法
- 原Android热更新开源项目Tinker源码解析系列之三(so热更新)
- Android—Service与Activity的交互
- android studio 不能创建或者安装模拟器
- android_m2repository_rxx.zip下载地址以及MD5
- Kotlin的Lambda表达式以及它们怎样简化Android开发(KAD 07)