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异常 解决办法 以下代 ...
随机推荐
- vue下载zip包到本地
<script> import axios from 'axios' export default{ methods: { downloadZip (downloadName, downl ...
- 四大组件之内容提容者ContentProvider
参考:Android开发基础之内容提容者ContentProvider Android四大组件 内容提供者是四大组件之一,还记得Android的四大组件吗? 前面我们学习了三大组件了,对吧! 其中有: ...
- redis 5.0.5集群部署与服务器宕机故障模拟
背景 业务稳定性要求需要一套redis集群来保障 因此采用 redis cluster 集群 环境 名称 ip地址 cpu 内存 master端口 slave端口 redis-651 10.65.6. ...
- 部署spingboot项目到云服务器踩坑记录
按教程部署mall电商系统 https://www.macrozheng.com/mall/deploy/mall_deploy_docker.html#docker环境安装 只记录SpringBoo ...
- P1002 [NOIP2002 普及组] 过河卒
P1002 [NOIP2002 普及组] 过河卒 题目见上. 一个经典的递推题 递推不会的看下面: https://www.cnblogs.com/haoningdeboke-2022/p/16247 ...
- Linux网络第五章:yum仓库的灵活部署及NFS共享服务
目录 一.yum仓库的灵活部署 1.yum基础知识及命令 2.本地yum仓库搭建 3.通过httpd服务建立yum仓库 4.建立国内yum源 二.NFS共享服务 1.NFS基础知识 2.搭建NFS服务 ...
- linux 高并发系统限制 设置
linux资源限制配置文件是/etc/security/limits.conf:限制用户进程的数量对于linux系统的稳定性非常重要. limits.conf文件限制着用户可以使用的最大文件数,最大线 ...
- Android自动化用例编写
java -jar appcrawler.jar<路径> --demo java -jar appcrawler.jar<路径> \ -c example.yml \ --c ...
- Usage of Seven Zip in C#
Compresss by Squid-Box.SevenZipSharp.Lite choose x86/x64 7z dll if (IntPtr.Size == 4) { SevenZipExtr ...
- #pragma directive
#pragma package(smart_init) #pragma package(smart_init)确保已打包的单元按照其依赖关系确定的顺序进行初始化(默认情况下包含在package(包)源 ...