android HttpURLConnection ,HttpClient设置Cookie
上一阶段项目设计使用cookie信息实现登录访问功能,在实现过程遇到一些问题,下面整理一下:
首先,client想使用cookie,必须访问一次server从会话中获取cookie信息,然后在设置回去,在android使用HttpURLConnection 直接设置会报异常
查阅文档及StackOver发现android需要使用CookieManager进行处理cookie相关信息,实现如下:
InputStream input = null;
OutputStream output = null; HttpURLConnection connection = null;
try {
java.net.CookieManager manager = new java.net.CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager); URL url = new URL(dnUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); connection.connect(); connection.getHeaderFields();
CookieStore store = manager.getCookieStore(); int resultCode=connection.getResponseCode();
responseUpdateCookieHttpURL(store);
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (resultCode != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
/**
* 更新本地Cookie信息
*/
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void responseUpdateCookieHttpURL(CookieStore store) {
boolean needUpdate = false;
List<HttpCookie> cookies = store.getCookies();
HashMap<String, String> cookieMap = null;
if (cookieMap == null) {
cookieMap = new HashMap<String, String>();
}
for (HttpCookie cookie : cookies) {
String key = cookie.getName();
String value = cookie.getValue();
if (cookieMap.size() == 0 || !value.equals(cookieMap.get(key))) {
needUpdate = true;
}
cookieMap.put(key, value);
// BDebug.e(HTTP_COOKIE, cookie.getName() + "---->" + cookie.getDomain() + "------>" + cookie.getPath());
} }
public static final int GET = 0;
public static final int POST = 1;
public static final String HTTP_POST_BODY = "body";
public static final String HTTP_COOKIE = "Cookie";
public static final String HTTP_USER_AGENT = "User-Agent";
HttpClient实现更改设置Cookie信息:
void handleCookie(String url){
try{
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = client.execute(httpget);
int responseCode = httpResponse.getStatusLine().getStatusCode();
HttpBuilder.responseUpdateCookieHttpClient((DefaultHttpClient)client);
if (responseCode == HttpStatus.SC_OK) {
/*result = EntityUtils.toString(httpResponse.getEntity());
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();*/
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 获取cookie信息
*
* @param cookieMap
* @return
*/
public static String getCookieInfo(HashMap<String, String> cookieMap) {
StringBuilder cookieInfo = new StringBuilder();
if (cookieMap != null && cookieMap.size() > 0) {
Iterator<Entry<String, String>> iter = cookieMap.entrySet().iterator();
Entry<String, String> entry;
while (iter.hasNext()) {
String key = "";
String value = "";
entry = iter.next();
key = entry.getKey();
value = entry.getValue();
cookieInfo.append(key).append("=").append(value).append(";");
}
}
return cookieInfo.toString();
} /**
* 更新本地Cookie信息
*
* @param defaultHttpClient
*/
public static void responseUpdateCookieHttpClient(DefaultHttpClient defaultHttpClient) {
boolean needUpdate = false;
List<Cookie> cookies = defaultHttpClient.getCookieStore().getCookies();
HashMap<String, String> cookieMap = null;
if (cookieMap == null) {
cookieMap = new HashMap<String, String>();
}
for (Cookie cookie : cookies) {
String key = cookie.getName();
String value = cookie.getValue();
if (cookieMap.size() == 0 || !value.equals(cookieMap.get(key))) {
needUpdate = true;
}
cookieMap.put(key, value);
} }
基本就这些,有问题留言。
android HttpURLConnection ,HttpClient设置Cookie的更多相关文章
- [Android] HttpURLConnection & HttpClient & Socket
Android的三种网络联接方式 1.标准Java接口:java.net.*提供相关的类//定义地址URL url = new URL("http://www.google.com" ...
- android webview setcookie 设置cookie
CookieSyncManager.createInstance(mWebView.getContext()); CookieManager cookieManager = CookieManager ...
- Android 给WebView设置Cookie
最近项目中用到WebView访问新浪支付页面,有个要求是必须是登录状态,否则会报Token过期,然后我简单的将我从cookie中取得的ticket,即一串数字可以代表用户登录的唯一标识作为参数拼接到u ...
- android httpUrlConnection HttpClient
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha httpUrlConnection 超文本传输协议统一资源定位器连接 http 超 ...
- android webview里获取和设置cookie
private class MyWebViewClient extends WebViewClient { public boolean shouldOverrideUrlLoading(WebVie ...
- 关于android webview 设置cookie的问题
转自:http://blog.csdn.net/encienqi/article/details/7912733 我们在android中访问网络经常会用到Apache的HttpClient,用此类去访 ...
- Android HttpURLConnection源代码分析
Android HttpURLConnection源代码分析 之前写过HttpURLConnection与HttpClient的差别及选择.后来又分析了Volley的源代码. 近期又遇到了问题,想在V ...
- android 给url添加cookie
前些天因为项目需要写了一个通过网络连接去服务端拿数据的方法,但是需要让程序添加上cookie,因为之前对cookie 没有怎么研究过(包括做web 那会也没有用过或者说很少用),所以 一时用起来不太会 ...
- Java通过httpclient获取cookie模拟登录
package Step1; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Htt ...
- Android HttpURLConnection.connect找不到源 HttpURLConnection连接失败 HttpURLConnection.connect IO异常 解决办法
Android HttpURLConnection.connect找不到源 HttpURLConnection连接失败 HttpURLConnection.connect IO异常 解决办法 以下代 ...
随机推荐
- 【Direct3D 12】配置编译环境
创建桌面应用程序 使用Visual Studio Community 2019创建一个桌面应用程序. 配置SDK版本.头文件.依赖库 右键单击创建的项目名称,选择Properties. 在Config ...
- 微信内h5调用支付
在做公众号商城的时候,需要用到调用微信支付,这是微信官方文档教程 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&in ...
- c++ class派生与多态
目录 类继承和类派生 继承时名字遮蔽 基类和派生类的构造函数 构造函数调用顺序 基类和派生类的析构函数 多重继承 虚继承和虚基类 将派生类赋值给基类(向上转型) 将派生类指针赋值给基类指针. 将派生类 ...
- KU060板卡设计资料原理图第636篇:基于FMC的KU060高性能 PCIe 载板
基于FMC的KU060高性能 PCIe 载板 一.板卡概述 板卡主控芯片采用Xilinx 公司的 Kintex UltraScale系列FPGA XCKU060-2FFVA1156.板载 2 组 64 ...
- [CSS]背景图片很大,根据屏幕缩小适配后,div之间有空隙的问题
RT.美术给的素材宽度是1080px的. 在不缩放的情况下,1080px宽度的屏幕显示div之间正常,没有空隙,但使用transform属性之后,div缩小,div之间有空隙(白线) 百度有人说给这些 ...
- 阿里云服务器 jdk1.8 安装配置
阿里云服务器 jdk1.8 安装配置 下载/上传 jdk安装包 解压到指定目录 重命名解压后的文件夹名称 配置环境变量 验证JAVA环境是否安装成功 step 0.安装包准备 1 wget --no ...
- (app笔记)Memory Fill内存填充
Memory Fill 是实现app内存填充工具(运行内存,物理内存,网络空间内存) Used:已用内存 filled:未回收内存 Free:自由内存 1.Ram(Total Ram):手机运行内存 ...
- nginx 配置443 域名
1 申请域名 (公有云)2 下载证书 pem key 并上传服务器指定目录3 公有云上做A记录解析 (解析到代理的nginx)4 nginx配置443模块 配置内容: server { listen ...
- pytorch学习笔记(9)--神经网络模型的保存与读取
一.网络模型的保存和加载 1.网络模型保存方法1 import torch import torchvision vgg16 = torchvision.models.vgg16(weights=Fa ...
- 为 windows 10 右键菜单加打开DOS窗口
创建一个批处理文件,输入以下行,保存执行即可. echo off reg add "HKCR\*\shell\ms-dos" /ve /d 打开DOS命令 /f reg add & ...