上一阶段项目设计使用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的更多相关文章

  1. [Android] HttpURLConnection & HttpClient & Socket

    Android的三种网络联接方式 1.标准Java接口:java.net.*提供相关的类//定义地址URL url = new URL("http://www.google.com" ...

  2. android webview setcookie 设置cookie

    CookieSyncManager.createInstance(mWebView.getContext()); CookieManager cookieManager = CookieManager ...

  3. Android 给WebView设置Cookie

    最近项目中用到WebView访问新浪支付页面,有个要求是必须是登录状态,否则会报Token过期,然后我简单的将我从cookie中取得的ticket,即一串数字可以代表用户登录的唯一标识作为参数拼接到u ...

  4. android httpUrlConnection HttpClient

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha httpUrlConnection    超文本传输协议统一资源定位器连接 http 超 ...

  5. android webview里获取和设置cookie

    private class MyWebViewClient extends WebViewClient { public boolean shouldOverrideUrlLoading(WebVie ...

  6. 关于android webview 设置cookie的问题

    转自:http://blog.csdn.net/encienqi/article/details/7912733 我们在android中访问网络经常会用到Apache的HttpClient,用此类去访 ...

  7. Android HttpURLConnection源代码分析

    Android HttpURLConnection源代码分析 之前写过HttpURLConnection与HttpClient的差别及选择.后来又分析了Volley的源代码. 近期又遇到了问题,想在V ...

  8. android 给url添加cookie

    前些天因为项目需要写了一个通过网络连接去服务端拿数据的方法,但是需要让程序添加上cookie,因为之前对cookie 没有怎么研究过(包括做web 那会也没有用过或者说很少用),所以 一时用起来不太会 ...

  9. Java通过httpclient获取cookie模拟登录

    package Step1; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Htt ...

  10. Android HttpURLConnection.connect找不到源 HttpURLConnection连接失败 HttpURLConnection.connect IO异常 解决办法

    Android HttpURLConnection.connect找不到源  HttpURLConnection连接失败 HttpURLConnection.connect IO异常 解决办法 以下代 ...

随机推荐

  1. 一些excel随笔,瞎记一下

    1 使用sumif函数的时候,如果对于一列0求值返回的时候,显示一个英文中的破折号例 "-" ,是数字格式可能设置为了会计专用,改回数值就行,要逗号的话点其他格式里面的数值,找一下 ...

  2. 关于精准UWB人员定位系统解决方案

    WB技术, 目前主要应用在室内定位.人员定位系统等定位领域.近年来被应用在无线定位和雷达测距应用中,因此作为民用雷达和民用测距取得了较快的发展.而今天,我们主要要来介绍的产品就是UWB技术的芯片DW1 ...

  3. 最大流模板(EK,Dinic

    一.EK EK算法:用bfs找增广路直到找不到为止.找到则更新最大流和残余网络,找不到则结束. 残余网络:对于一条走过的边,其正向边权值减少相应值,反向边权值增加相应值(用于反悔). 增广路:从所求起 ...

  4. 教你快速理解Linux虚拟化网络的全脉络,正确配置网络联通性。

    https://www.bilibili.com/video/BV1iy4y177f4?p=12 实用的干货快先码起来,说不定以后会用到哟

  5. 二分查找中mid值的计算方法

    在刷题的时候遇到许多二分查找的题目 发现很多大佬的题解中mid值得计算都是用的:mid = low + (high-low)/ 2; 为什么不用mid = (low+high)/ 2的计算方法呢? i ...

  6. springboot启动报错 Failed to scan *****/derbyLocale_ja_JP.jar from classloader hierarchy

    springboot启动报错 Failed to scan *****/derbyLocale_ja_JP.jar from classloader hierarchy   这两天自己在玩虚拟机,想把 ...

  7. 树莓派 Zero W 安装 apache2 + php

    ※ 树莓派Zero W ,默认 hostname为 raspberrypi ,通过USB网络方式登陆时,修改hostname后,登录主机名要随之变化. ① ssh pi@raspberrypi 更新系 ...

  8. usb 2.0的状态跳转图

  9. safari iframe 滚动问题(iframe--- iphone中的iframe没有滚动,要设置滚动;)

    _::-webkit-full-page-media, _:future, :root #frameBody>.frame-pnl{ overflow:auto; -webkit-overflo ...

  10. js之new的原理和源码

    new的原理即作用: function Student(name,age){ this.name=name; this.age=age; } var stu=new Student("小明& ...