我如何使用cookie Android上的http请求?如何使用、cookie、http、Android

2023-09-11 11:47:23 作者:夏栀

我想提出一个HTTP请求到远程服务器,同时妥善处理Cookie(由服务器发送如:存储的cookie和发送这些cookie,当我进行后续请求)。它会是不错的preserve任何和所有的cookies,但实际上我唯一关心的是会话cookie。

I'd like to make an http request to a remote server while properly handling cookies (eg. storing cookies sent by the server, and sending those cookies when I make subsequent requests). It'd be nice to preserve any and all cookies, but really the only one I care about is the session cookie.

使用java.net,看来,preferred办法做到这一点是使用java.net.CookieHandler(抽象基类)和java.net.CookieManager(具体实现)。 Android有java.net.CookieHandler,但它似乎不具备java.net.CookieManager。

With java.net, it appears that the preferred way to do this is using java.net.CookieHandler (abstract base class) and java.net.CookieManager (concrete implementation). Android has java.net.CookieHandler, but it does not seem to have java.net.CookieManager.

我可以$ C C这一切$用手通过检查HTTP头,但似乎必须有一个更简单的方法。

I could code it all by hand by inspecting http headers, but it seems like there must be an easier way.

什么是正确的方法,使Android上的http请求,同时preserving饼干?

What is the proper way to make http requests on Android while preserving cookies?

推荐答案

事实证明,谷歌Android附带提供了Apache的HttpClient 4.0,而我能弄清楚如何使用基于表单的登录的例子做的 HttpClient的文档:

It turns out that Google Android ships with Apache HttpClient 4.0, and I was able to figure out how to do it using the "Form based logon" example in the HttpClient docs:

http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/httpclient/src/examples/org/apache/http/examples/client/ClientFormLogin.java

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

/**
 * A example that demonstrates how HttpClient APIs can be used to perform
 * form-based logon.
 */
public class ClientFormLogin {

    public static void main(String[] args) throws Exception {

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }
        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
                "org=self_registered_users&" +
                "goto=/portal/dt&" +
                "gotoOnFail=/portal/dt?error=true");

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("IDToken1", "username"));
        nvps.add(new BasicNameValuePair("IDToken2", "password"));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        response = httpclient.execute(httpost);
        entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }

        System.out.println("Post logon cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        // When HttpClient instance is no longer needed, 
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();        
    }
}