上一阶段项目设计使用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. 判断js对象每个字段是否为空

    for(var key in obj) { if (!obj[key])return; }

  2. python使用win32gui操作窗口

    激活指定窗口 import win32gui import win32con def match_windows(win_title): """ 查找指定窗口 :para ...

  3. 力扣(leetcode)题库0001-python3

    试一下leetcode的题库,不知道对于我这种小白要多长时,但是目标已经种下,去做就是了.You can do anything you set your mind to. 题目:题库链接 中:给定一 ...

  4. Tiup离线安装TIDB集群4.0.16版本

    环境:centos7.6 中控机:8.213.8.25(内网) 可用服务器8.213.8.25-8.213.8.29 一.准备 TiUP 离线组件包 方法1:外网下载离线安装包拷贝进内网服务器 在Ti ...

  5. java.net.ConnectException: Your endpoint configuration is wrong; For more details see: http://wiki.apache.org/hadoop/UnsetHostnameOrPort

    今天使用在hive中建表,并在hive中将查询到的语句插入到新表中时,一直开在如图所示位置不动 等待了20多分钟,然后报了这么个错 java.net.ConnectException: Your en ...

  6. CCF 201909-1 小明种苹果

    #include <iostream> #include <bits/stdc++.h> #include <string> using namespace std ...

  7. (一)用go实现单链表

    本篇,我们用go简单的实现单链表这种数据结构. 1.节点定义 type Node struct{ data int next *Node } 2.节点的添加 // 尾插法插入节点 func (p *N ...

  8. java时间日期API

    package java1; import org.junit.Test; import java.util.Date; /** * @author 高槐玉 * #Description JDK 8之 ...

  9. 《【转载】ChatGPT创始人,给我们上的8堂课》 回复

    <[转载]ChatGPT创始人,给我们上的8堂课>           https://tieba.baidu.com/p/8276644432

  10. 初次使用gitee的笔记

    步骤及问题 1.git config --global user.name "username" 2.git config --global user.email "us ...