您的位置:首页 > 理论基础 > 计算机网络

Android HttpClient使用Cookie应用分析

2014-05-29 21:59 435 查看
public class MainActivity extends Activity {

private AndroidHttpClient mHttpclient=AndroidHttpClient.newInstance("");

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

findViewById(R.id.button1).setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

new Thread(rTest).start();

}

});

}

private String toString(InputStream is) throws IOException{

String ret="";

InputStreamReader isr=new InputStreamReader(is);

BufferedReader br=new BufferedReader(isr);

String tmp=br.readLine();

while(tmp!=null){

ret+=tmp;

tmp=br.readLine();

}

br.close();

return ret;

}

private Runnable rTest=new Runnable() {

@Override

public void run() {

// TODO Auto-generated method stub

try {

BasicHttpContext context=new BasicHttpContext();

context.setAttribute(ClientContext.COOKIE_STORE,new BasicCookieStore());

HttpPost httppost = new HttpPost("http://10.226.233.48:8080/WebApplication1/LogIn");

List <NameValuePair> nvps = new ArrayList <NameValuePair>();

nvps.add(new BasicNameValuePair("info", "你好 世界!!"));

httppost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));

HttpResponse response=mHttpclient.execute(httppost,context);

HttpEntity entity = response.getEntity();

Log.i("kagami", MainActivity.this.toString(entity.getContent()));

entity.consumeContent();

HttpGet httpget2 = new HttpGet("http://10.226.233.48:8080/WebApplication1/Info");

HttpResponse response2=mHttpclient.execute(httpget2,context);

HttpEntity entity2 = response2.getEntity();

Log.i("kagami", MainActivity.this.toString(entity2.getContent()));

entity2.consumeContent();

}catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

};



AndroidHttpClient和DefaultHttpClient的区别:

AndroidHttpClient不能在主线程中execute,会抛出异常。AndroidHttpClient通过静态方法newInstance获得实例,参数是代理,不用代理的话填“”。DefaultHttpClient默认是启用Cookie的,AndroidHttpClient默认不启用Cookie,要使用的话每次execute时要加一个HttpContext参数,并且添加CookieStore。用完后别忘了close不然不能创建新实例。

详细出处参考:http://www.jb51.net/article/32196.htm

httpclient与webview需要进行cookie 共享,因为如果不共享,那么假设你在httpclient进行了登录,然后用webview里打开那些login之后才能看的page,就会叫你再login

[java]
view plaincopyprint?

DefaultHttpClient httpclient=....;
String toUrl="https://cap.cityu.edu.hk/studentlan/details.aspx.....";

List<Cookie> cookies = httpclient.getCookieStore().getCookies();

if (! cookies.isEmpty()){
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
//sync all the cookies in the httpclient with the webview by generating cookie string

for (Cookie cookie : cookies){
String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();
cookieManager.setCookie(toUrl, cookieString);
CookieSyncManager.getInstance().sync();
}

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.HttpEntity;

import org.apache.http.HttpHost;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.methods.HttpUriRequest;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.protocol.BasicHttpContext;

import org.apache.http.protocol.ExecutionContext;

import org.apache.http.protocol.HttpContext;

import org.apache.http.util.EntityUtils;

import android.util.Log;

public class Login_http {

private String username; // 用户名

private String password;// 用户密码

private int state;

private String result;// 返回的数据

private String HOST = "http://210.36.16.166";// 主机

private String Land_Url = "http://210.36.16.166/success.yws";// 登陆地址

private String method;

private String cookie_id;

private String cookie_id_end;

private HttpClient client;

private HttpContext httpcontext ;

public Login_http(String username, String password) {

super();

this.username = username;

this.password = password;

Login_In();

}

// 实现登陆

public void Login_In() {

httpcontext= new BasicHttpContext();

client = new DefaultHttpClient();

HttpResponse responsepost;

HttpResponse responseget;

HttpResponse userinforesponse;

// 存放用户名和密码

List<NameValuePair> formparams = new ArrayList<NameValuePair>();

formparams.add(new BasicNameValuePair("username", username));

formparams.add(new BasicNameValuePair("password", password));

UrlEncodedFormEntity urlentity;

try {

urlentity = new UrlEncodedFormEntity(formparams, "UTF-8");

HttpPost post = new HttpPost(Land_Url);

post.addHeader("Referer", "http://210.36.16.166/index.yws");

post.addHeader("Accept",

"text/javascript, text/html, application/xml, text/xml");

post.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");

post.addHeader("Accept-Encoding", "gzip,deflate");

post.addHeader("Connection", "Keep-Alive");

post.addHeader("Cache-Control", "no-cache");

post.addHeader("Cookie", cookie_id);

post.addHeader("Host", "210.36.16.166");

post.addHeader("Location", "http://210.36.16.166/index.yws");

post.setEntity(urlentity);

responsepost = client.execute(post, httpcontext);HttpGet get = new HttpGet("http://bbs.newgxu.cn/index.yws");

responseget = client.execute(get);

HttpEntity entity1 = responsepost.getEntity();

HttpEntity entity2 = responseget.getEntity();

//System.out.println(EntityUtils.toString(entity1));

result = EntityUtils.toString(entity2);// 返回结果

//Log.i("EntityUtils", result);

state = responsepost.getStatusLine().getStatusCode();// 200是联网正常

HttpUriRequest successurl = (HttpUriRequest) httpcontext

.getAttribute(ExecutionContext.HTTP_REQUEST);

System.out.println(successurl.getURI().toString());

HttpGet userinfo=new HttpGet("http://bbs.newgxu.cn/user/upgrade.yws");

userinforesponse=client.execute(userinfo);

HttpEntity userentity=userinforesponse.getEntity();

System.out.println(EntityUtils.toString(userentity));

if (successurl.getURI().toString().equals("/success.yws")) {

System.out.println("登陆成功!");

System.out

.println("dcfvgwdfgdiufhduiofheifh" + result.length());

}else {

System.out.println( "登陆失败");

}

}catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

面的 post 可以 成功 登陆。账号 (a1008611)密码(a1008611)

但我要登陆 后 http://bbs.newgxu.cn/user/upgrade.yws 的信息。却被重 定向到 登陆 界面了(http://bbs.newgxu.cn/login.yws)?

在这也可以 登陆!!
http://bbs.newgxu.cn/index.yws
要登录 才能 看见 的网页(http://bbs.newgxu.cn/user/upgrade.yws)否则 会被 重定向 想到 登陆 界面。

我用的是 android 4.1 jar包。是不是 这里的apache 的jar 包 cookie 不会自动 保存 啊?

求教 ,谢谢!!




小无赖

发帖于 1年前

3回/2075阅

标签:
HttpClient


Android

举报
| 分享到

0

收藏(2)

按票数排序

显示最新答案 共有3个答案

(最后回答: 1年前)

1




迷途d书童
1年前

responsepost = client.execute(post, httpcontext);

post方式执行后应该记录下cookie,get方式执行前也应该像post那样添加cookie到Header信息里。




--- 共有 1 条评论 ---

龙凯
但 httpclient 不是自动处理 cookie 吗?如果 自己 写 应该 如何 记录cookie?
(1年前) 回复

评论(1)|
引用此答案| 举报

1




迷途d书童
1年前

view source

print?

01
List<Cookie> cookies = client.getCookieStore().getCookies();
02
if
(!cookies.isEmpty()) {
03
for

(Cookie cookie : cookies) {
04
String cookie_domain = cookie.getDomain();
05
String cookie_name = cookie.getName());
06
String cookie_value = cookie.getValue());
07
String cookie_version = cookie.getVersion();
08
String cookie_path = cookie.getPath();
09
}

10
}
--- 共有 1 条评论 ---

小无赖
得到cookie的多个属性,如何使用,让两级网页使用同一cookie便别身份。本人有点菜。麻烦了!谢谢了。
(1年前) 回复

评论(1)|
引用此答案| 举报

0




小无赖
1年前

得到cookie的多个属性,如何使用,让两级网页使用同一cookie便别身份。本人有点菜。麻烦了!谢谢了。

--- 共有 4 条评论 ---

小无赖
回复
@迷途d书童 : 有cookie ,刚刚试过了! (1年前) 回复

小无赖
回复
@迷途d书童 : 对了 如果 他后台 不用cookie 验证那么也就 没办法 了吗? (1年前)
回复

小无赖
回复
@迷途d书童 : 额 麻烦 了 谢谢 ,我看看 如何 办吧!! (1年前)
回复

迷途d书童
这个需要你自己在后台做好生成和验证cookie的处理,比如生成cookie的时候带上userID,验证cookie的时候跟据你自己定
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: