作者:幸福的xinwangnanfei_736 | 来源:互联网 | 2023-10-11 08:03
最近做项目在手机端登录Http请求和WebView记载登录获取Cookie信息,可查看Cookie信息。如图:Http请求获取Cookie信息:publicst
最近做项目在手机端登录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> COOKIE_map = connection.getHeaderFields();
List COOKIEs = COOKIE_map.get("Set-COOKIE");
if (null != COOKIEs && 0 String s = "";
for (String COOKIE : COOKIEs) {
if (s.isEmpty()) {
s = COOKIE;
} else {
s += ";" + COOKIE;
}
}
Log.i("ss", 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);
}
});
源码点击下载:https://github.com/DickyQie/android-webview