android - HttpPost cookie 持久化 android

标签 android http-post httpclient cookiestore

我想在发布请求后保存 cookie。 httpClient实现类:

 public class JSONParser {
    CookieStore store = new BasicCookieStore();
       static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
        private static final DefaultHttpClient httpClient = new DefaultHttpClient() ;
     public static DefaultHttpClient getInstance() { return httpClient; }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            CookieStore cookieStore = new BasicCookieStore();

            // Create local HTTP context
            HttpContext localContext = new BasicHttpContext();

            // Bind custom cookie store to the local context
            localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

            DefaultHttpClient httpClient = JSONParser.getInstance();
            List<Cookie> cookies = httpClient.getCookieStore().getCookies();
            httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Android-AEApp,ID=2435743");
            httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            httpPost.setHeader("User-Agent","Android-AEApp,ID=2435743");

            cookies = httpClient.getCookieStore().getCookies();
            httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpPost.setHeader("Cookie", "PHPSESSID=lc89a2uu0rj6t2p219gc2cq4i2; path=/");
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            cookies = httpClient.getCookieStore().getCookies();

            if (cookies.isEmpty()) {
                for (Cookie a : cookies)
                cookieStore.addCookie(a);
            } else {
                for (Cookie a : cookies) {
                    cookieStore.addCookie(a);
                    System.out.println("- " + a.getValue().toString());
                }
            }

            is = httpEntity.getContent();


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
       }

我为我的 DefaultHttpClient 创建了单色调,并希望将其用于进一步的请求。当我尝试这样做时:

 HttpResponse httpResponse = httpClient.execute(httpPost, localContext);

我没有 cookies 。当我不包含 localContext 时,我可以使用

获取 cookie
 if (cookies.isEmpty()) {
                for (Cookie a : cookies)
                cookieStore.addCookie(a);
            } else {
                for (Cookie a : cookies) {
                    cookieStore.addCookie(a);
                    System.out.println("- " + a.getValue().toString());
                }
            }

但是 cookie 不会在第二次请求时设置。我猜 - 原因在于不使用 localContext。告诉我问题是什么,如果它们一直在变化,我该如何设置 cookie?

最佳答案

我将 Singleton 用于我的 Cookie 的 ArrayList。它看起来像这样:

public class CookieStorage {


    private ArrayList<Object> arrayList;

    private static CookieStorage instance;

    private CookieStorage(){
        arrayList = new ArrayList<Object>();
    }

    public static CookieStorage getInstance(){
        if (instance == null){
            instance = new CookieStorage();
        }
        return instance;
    }

    public ArrayList<Object> getArrayList() {
        return arrayList;
    }

    @Override
    public String toString()
    {       
    return getArrayList().toString();   
    }
}

还有我的 HttpClient 类:

public class HttpClient {
static InputStream is = null;
private static final DefaultHttpClient httpClient = new DefaultHttpClient() ;
public static DefaultHttpClient getInstance() { return httpClient; }

 public static InputStream getResponse(String url, List<NameValuePair> params)
 {
    try {
    CookieStore cookieStore = new BasicCookieStore();
    DefaultHttpClient httpClient = JSONParser.getInstance();        
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Android-AEApp,ID=2435743");
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
    BasicClientCookie cookie = new BasicClientCookie("PHPSESSID", "1");  
    httpClient.setCookieStore(cookieStore);
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(params));
    httpPost.setHeader("User-Agent","Android-AEApp,ID=2435743");
    httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    System.out.println(CookieStorage.getInstance().toString());
    if (CookieStorage.getInstance().getArrayList().isEmpty())
        CookieStorage.getInstance().getArrayList().add("PHPSESSID=lc89a2uu0rj6t2p219gc2cq4i2");
    httpPost.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
    HttpResponse httpResponse = httpClient.execute(httpPost);
    Header[] head = httpResponse.getAllHeaders();
    System.out.println(cookie);

    if (httpResponse.getLastHeader("Set-Cookie")!=null)
    {

        CookieStorage.getInstance().getArrayList().remove(0);
        CookieStorage.getInstance().getArrayList().add(httpResponse.getLastHeader("Set-Cookie").getValue());
    }
    Log.i("arrayList",(CookieStorage.getInstance().getArrayList().toString()));

    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

     return is;
 }


}

关于android - HttpPost cookie 持久化 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11938283/

相关文章:

java - 如何初始化在 Activity 中定义的界面,该界面是通过 TabLayout 使用 ViewPager 设置的 3 个 fragment 实现的?

ios - 如何使用 JSON 格式的参数在 byteArray 中发送图像 iOS swift4

javascript - 如何从 jQuery 异常中获取消息

php - 使用 PHP 格式化 HTTP POST 请求中的数据

Android Studio 4.1.1-MacOS BigSur - 全屏卡住问题

android - 写入SD卡

java - 尝试更改 android 上的 Firebase 数据库中的值时循环

android - 如何设置httpclient的字符编码

c# - IIS 服务器上的 Web API 内的 Httpclient GetAsync 失败(503 服务不可用)

java - HttpClient、ConnectionManager 和奇怪的池限制