@Override
  public void writeExternal(ObjectOutput output) throws IOException {
    String data;
    Date date;
    List<Cookie> cookie_list = getCookies();
    output.writeInt(cookie_list.size());
    for (Cookie cookie : cookie_list) {
      output.writeUTF(cookie.getName());
      output.writeUTF(cookie.getValue());

      data = cookie.getComment();
      output.writeBoolean(data != null);
      if (data != null) output.writeUTF(data);

      date = cookie.getExpiryDate();
      output.writeBoolean(date != null);
      if (date != null) output.writeLong(date.getTime());

      data = cookie.getDomain();
      output.writeBoolean(data != null);
      if (data != null) output.writeUTF(data);

      data = cookie.getPath();
      output.writeBoolean(data != null);
      if (data != null) output.writeUTF(data);

      output.writeBoolean(cookie.isSecure());
      output.writeInt(cookie.getVersion());
    }
  }
  protected synchronized void clearCookieForHost(String sessionHost) throws Exception {
    Cookie sessionCookie = null;
    for (Cookie cookie : cookieStore.getCookies()) {
      String cookieDomain = cookie.getDomain();
      if (cookieDomain != null) {
        if (sessionHost.equals(cookieDomain)
            || sessionHost.indexOf(cookieDomain) != -1
            || cookieDomain.indexOf(sessionHost) != -1) {
          sessionCookie = cookie;
          break;
        }
      }
    }

    if (sessionCookie != null) {
      BasicClientCookie httpCookie =
          new BasicClientCookie(sessionCookie.getName(), sessionCookie.getValue());
      httpCookie.setExpiryDate(new Date(0));
      httpCookie.setVersion(1);
      httpCookie.setPath(sessionCookie.getPath());
      httpCookie.setDomain(sessionCookie.getDomain());
      cookieStore.addCookie(httpCookie);
    }

    cookieStore.clearExpired(new Date()); // this should clear the cookie
  }
示例#3
0
 private void cookieToPrefs(Cookie cookie, SyncedStore.Editor e) {
   final String name = cookie.getName();
   e.putString(COOKIE_PREFIX + name + "value", cookie.getValue());
   e.putString(COOKIE_PREFIX + name + "path", cookie.getPath());
   e.putString(COOKIE_PREFIX + name + "domain", cookie.getDomain());
   e.putString(COOKIE_PREFIX + name + "expiry", stringFromDate(cookie.getExpiryDate()));
 }
 public boolean match(final Cookie cookie, final CookieOrigin origin) {
   if (cookie == null) {
     throw new IllegalArgumentException("Cookie may not be null");
   }
   if (origin == null) {
     throw new IllegalArgumentException("Cookie origin may not be null");
   }
   String targetpath = origin.getPath();
   String topmostPath = cookie.getPath();
   if (topmostPath == null) {
     topmostPath = "/";
   }
   if (topmostPath.length() > 1 && topmostPath.endsWith("/")) {
     topmostPath = topmostPath.substring(0, topmostPath.length() - 1);
   }
   boolean match = targetpath.startsWith(topmostPath);
   // if there is a match and these values are not exactly the same we have
   // to make sure we're not matcing "/foobar" and "/foo"
   if (match && targetpath.length() != topmostPath.length()) {
     if (!topmostPath.endsWith("/")) {
       match = (targetpath.charAt(topmostPath.length()) == '/');
     }
   }
   return match;
 }
 private void writeObject(ObjectOutputStream out) throws IOException {
   out.writeObject(cookie.getName());
   out.writeObject(cookie.getValue());
   out.writeObject(cookie.getComment());
   out.writeObject(cookie.getDomain());
   out.writeObject(cookie.getExpiryDate());
   out.writeObject(cookie.getPath());
   out.writeInt(cookie.getVersion());
   out.writeBoolean(cookie.isSecure());
 }
示例#6
0
 private void cookieToBundle(Cookie cookie, Bundle b) {
   final String name = cookie.getName();
   b.putString(COOKIE_PREFIX + name + "value", cookie.getValue());
   b.putString(COOKIE_PREFIX + name + "path", cookie.getPath());
   b.putString(COOKIE_PREFIX + name + "domain", cookie.getDomain());
   final Date expiryDate = cookie.getExpiryDate();
   if (null != expiryDate) {
     b.putString(COOKIE_PREFIX + name + "expiry", stringFromDate(expiryDate));
   }
 }
示例#7
0
 /**
  * Creates a new HtmlUnit cookie from the HttpClient cookie provided.
  *
  * @param c the HttpClient cookie
  */
 public Cookie(final org.apache.http.cookie.Cookie c) {
   this(
       c.getDomain(),
       c.getName(),
       c.getValue(),
       c.getPath(),
       c.getExpiryDate(),
       c.isSecure(),
       ((ClientCookie) c).getAttribute("httponly") != null);
 }
 public void validate(final Cookie cookie, final CookieOrigin origin)
     throws MalformedCookieException {
   if (!match(cookie, origin)) {
     throw new MalformedCookieException(
         "Illegal path attribute \""
             + cookie.getPath()
             + "\". Path of origin: \""
             + origin.getPath()
             + "\"");
   }
 }
示例#9
0
  @Override
  public synchronized void addCookie(Cookie cookie) {

    super.addCookie(cookie);
    String name = cookie.getName();

    Cookie existing = null;
    SyncedStore.Reader r = mSharedPreferences.read();
    try {
      existing = cookieFromPrefs(r, name);
    } finally {
      r.complete();
    }

    if (existing == null
        || !existing.getValue().equals(cookie.getValue())
        || !existing.getPath().equals(cookie.getPath())
        || !existing.getDomain().equals(cookie.getDomain())
        || !existing.getExpiryDate().equals(cookie.getExpiryDate())) {

      SyncedStore.Editor e = mSharedPreferences.edit();
      try {
        // clear the existing cookie from prefs.
        String prefix = COOKIE_PREFIX + name;
        for (String k : e.keySet()) {
          if (k.startsWith(prefix)) {
            e.remove(k);
          }
        }

        // and then, if new cookie is persistent, then add it!
        if (cookie.getExpiryDate() != null) {
          cookieToPrefs(cookie, e);
        }
      } finally {
        e.commit();
      }
    }
  }
  private void saveCookiesToPreferences(Context context, DefaultHttpClient client) {
    final SharedPreferences sharedPreferences =
        context.getSharedPreferences(SHARED_PREFERENCES_NAME_SUMC_COOKIES, Context.MODE_PRIVATE);
    final Editor edit = sharedPreferences.edit();
    edit.clear();

    int i = 0;
    for (Cookie cookie : client.getCookieStore().getCookies()) {
      edit.putString(PREFERENCES_COOKIE_NAME + i, cookie.getName());
      edit.putString(PREFERENCES_COOKIE_VALUE + i, cookie.getValue());
      edit.putString(PREFERENCES_COOKIE_DOMAIN + i, cookie.getDomain());
      edit.putString(PREFERENCES_COOKIE_PATH + i, cookie.getPath());
      i++;
    }
    edit.commit();
  }
 public String getPath() {
   return cookie.getPath();
 }
示例#12
0
  public boolean login() throws HTTPException {
    LoginParameters loginParameters = new LoginParameters();

    // Check the client cookies.  If 'enwikiUserID', 'enwikiUserName', and 'centralauth_Token' are
    // valid, already logged in.
    List<Cookie> cookies = client.getCookieStore().getCookies();
    int numCookieFound = 0;
    Iterator<Cookie> cookieItr = cookies.iterator();
    while (cookieItr.hasNext()) {
      Cookie cookie = cookieItr.next();
      if (cookie.getName().equalsIgnoreCase("enwikiUserID")) numCookieFound++;
      else if (cookie.getName().equalsIgnoreCase("enwikiUsername")) numCookieFound++;
      else if (cookie.getName().equalsIgnoreCase("centralauth_Token")) numCookieFound++;
      if (numCookieFound == 3) return true;
    }

    // Send the initial login request
    String loginQuery =
        url + "api.php?action=login&lgname=" + username + "&lgpassword="******"&format=xml";
    HttpPost loginRequest = new HttpPost(loginQuery);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody;
    try {
      responseBody = client.execute(loginRequest, responseHandler);
    } catch (ClientProtocolException e) {
      throw new HTTPException("An HTTP protocol error occurred.");
    } catch (IOException e) {
      e.printStackTrace();
      throw new HTTPException("The connection was aborted.");
    }
    loginParameters.setXMLParameters(responseBody);

    // Send the confirm token request
    String confirmTokenQuery =
        url
            + "api.php?action=login&lgname="
            + username
            + "&lgpassword="******"&lgtoken="
            + loginParameters.getToken()
            + "&format=xml";
    HttpPost confirmTokenRequest = new HttpPost(confirmTokenQuery);
    try {
      responseBody = client.execute(confirmTokenRequest, responseHandler);
    } catch (ClientProtocolException e) {
      throw new HTTPException("An HTTP protocol error occurred.");
    } catch (IOException e) {
      throw new HTTPException("The connection was aborted.");
    }
    loginParameters.setXMLParameters(responseBody);

    // Save the cookie information.
    cookies = client.getCookieStore().getCookies();
    cookieItr = cookies.iterator();
    ArrayList<String> cookieInfo = new ArrayList<String>();
    while (cookieItr.hasNext()) {
      Cookie cookie = cookieItr.next();
      if (cookie.isPersistent() && !cookie.isExpired(new Date())) {
        String cookieDetails =
            cookie.getComment()
                + ","
                + cookie.getCommentURL()
                + ","
                + cookie.getDomain()
                + ","
                + cookie.getName()
                + ","
                + cookie.getPath()
                + ","
                + cookie.getValue()
                + ","
                + cookie.getVersion()
                + ","
                + cookie.getExpiryDate().toString();
        cookieInfo.add(cookieDetails);
      }
    }
    addCookiesToFile(cookieInfo);

    return false;
  }
示例#13
0
  /**
   * http网页内容抓取
   *
   * @param url String 网页地址
   * @param timeoutSeconds int 超时时间(单位秒)
   * @param params Map<String, String> HTTPHead参数
   * @param cookieStore CookieStore 网页cookie
   * @return
   */
  public static String sendGet(
      Context mContext,
      String url,
      int timeoutSeconds,
      Map<String, String> params,
      CookieStore cookieStore,
      boolean isSaveCookie) {
    String result = null;
    Log.v(TAG, "httpGet start to get url:" + url);
    HttpParams httpParams = new BasicHttpParams();
    HttpContext context = new BasicHttpContext();

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
    WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
    if (!wifiManager.isWifiEnabled()) {
      Uri uri = Uri.parse("content://telephony/carriers/preferapn"); // 获取当前正在使用的APN接入点
      Cursor mCursor = mContext.getContentResolver().query(uri, null, null, null, null);
      if (mCursor != null && mCursor.getCount() > 0) {
        mCursor.moveToNext();
        String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
        if (proxyStr != null && proxyStr.trim().length() > 0) {
          Log.v(TAG, "wap proxy:" + proxyStr);
          HttpHost proxy = new HttpHost(proxyStr, 80);
          httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        }
      }
    }

    HttpConnectionParams.setConnectionTimeout(httpParams, timeoutSeconds * 1000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutSeconds * 1000);
    HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

    HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);

    if (cookieStore != null) {

      httpClient.setCookieStore(cookieStore);
      context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    }

    HttpGet httpGet = new HttpGet(url);
    httpGet.setHeader(
        "User-Agent",
        "Mozilla/5.0 (Linux; U; Android "
            + Build.VERSION.RELEASE
            + "; Zh-cn; "
            + Build.MODEL
            + " )AppleWebKit/528.5+(KHTML,like Gecko)Version/3.1.2 Mobile Safari/525.20.1");
    if (params != null) {
      Iterator<String> ite = params.keySet().iterator();
      while (ite.hasNext()) {
        String key = (String) ite.next();
        String value = (String) params.get(key);
        httpGet.addHeader(key, value);
      }
    }
    try {
      HttpResponse response = httpClient.execute(httpGet, context);
      if (isSaveCookie) {
        CookieStore cookieStores = httpClient.getCookieStore();
        if (cookieStores != null) {
          List<Cookie> listCookie = cookieStores.getCookies();
          int len = listCookie.size();
          for (int i = 0; i < len; i++) {
            Cookie cookie = listCookie.get(i);
            StringBuffer sb = new StringBuffer();
            sb.append(cookie.getName() + "=" + cookie.getValue() + ";\n");
            sb.append("domain=" + cookie.getDomain() + ";\n");
            sb.append("path=" + cookie.getPath() + ";\n");
            sb.append("expiry=" + cookie.getExpiryDate() + ";\n");
            Log.i(TAG, sb.toString());
          }
        }
        //				Config.getInstance().setCookieStroe(httpClient.getCookieStore());
      }
      int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode == 200) {
        result = EntityUtils.toString(response.getEntity());
      } else {
        Log.v(TAG, "result:" + EntityUtils.toString(response.getEntity()));
        result = MessageModel.RESPONSE_EXCEPTION;
        Log.e(TAG, "Network Exception, statusCode:" + statusCode);
      }
    } catch (Exception e) {
      if (e instanceof SocketTimeoutException) {
        result = MessageModel.CONNECTION_TIMEOUT;
        Log.e(TAG, "CONNECTION_TIMEOUT---- Network Exception:" + e.getMessage() + " url:" + url);
        e.printStackTrace();
      } else {
        result = MessageModel.RESPONSE_EXCEPTION;
        Log.e(TAG, "RESPONSE_EXCEPTION ---- Network Exception:" + e.getMessage() + " url:" + url);
        e.printStackTrace();
      }
    } finally {
      httpClient.getConnectionManager().shutdown();
    }
    Log.v(TAG, "httpGet get result:" + result);
    return result;
  }