Android HttpClient使用Cookie应用分析

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


  1. DefaultHttpClient httpclient=....;  
  2. String toUrl="https://cap.cityu.edu.hk/studentlan/details.aspx.....";  
  3.   
  4. List<Cookie> cookies = httpclient.getCookieStore().getCookies();  
  5.   
  6. if (! cookies.isEmpty()){  
  7.     CookieSyncManager.createInstance(this);  
  8.     CookieManager cookieManager = CookieManager.getInstance();  
  9.         //sync all the cookies in the httpclient with the webview by generating cookie string   
  10.     for (Cookie cookie : cookies){  
  11.         String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();  
  12.         cookieManager.setCookie(toUrl, cookieString);  
  13.         CookieSyncManager.getInstance().sync();  
  14.     }  

 

 

protected  void  onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         textView = (TextView)findViewById(R.id.showhtml);
         webView = (WebView)findViewById(R.id.showhtmlinwebview);    
         String baseUrl =  "http://xxxx.xxx.com" ;
         HttpGet getMethod =  new  HttpGet(baseUrl);
         getMethod.setHeader("Cookie""session_id=\"xxx==|xxxxx|xxxx\"");
         HttpClient httpClient =  new  DefaultHttpClient();
         try  {
             HttpResponse response = httpClient.execute(getMethod);  //发起GET请求
             Log.i(TAG,  "resCode = "  + response.getStatusLine().getStatusCode());  //获取响应码
             String htmlResponse = EntityUtils.toString(response.getEntity(),  "utf-8" );          
                     System.out.println(htmlResponse);
             webView.getSettings().setJavaScriptEnabled( true );
             webView.loadData(htmlResponse,  "text/html" "utf-8" );
         catch  (ClientProtocolException e) {
             e.printStackTrace();
         catch  (IOException e) {
             e.printStackTrace();
         }
     }

 

 

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 = " 主机
    private String Land_Url = "
登陆地址
    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阅

按票数排序  显示最新答案   共有3个答案 (最后回答: 1年前)

  • 1
  • 迷途d书童
    responsepost = client.execute(post, httpcontext);

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

    --- 共有 1 条评论 ---
    • 龙凯 但 httpclient 不是自动处理 cookie 吗?如果 自己 写 应该 如何 记录cookie? (1年前)   回复
    1
  • 迷途d书童
    01List<Cookie> cookies = client.getCookieStore().getCookies();   
    02if (!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年前)   回复
    0
  • 小无赖

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

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

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值