@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());
    }
  }
예제 #2
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()));
 }
 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());
 }
예제 #4
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));
   }
 }
예제 #5
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);
 }
예제 #6
0
 // 检查过期时间
 private boolean checkExperid(List<Cookie> cookies) {
   for (Cookie cookie : cookies) {
     if ("ue".equals(cookie.getName())) {
       Date now = new Date();
       if (now.compareTo(cookie.getExpiryDate()) > 0) {
         return false;
       }
     }
   }
   return true;
 }
예제 #7
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();
      }
    }
  }
 public Date getExpiryDate() {
   return cookie.getExpiryDate();
 }
예제 #9
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;
  }
예제 #10
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;
  }