예제 #1
0
 public boolean hasCookies() {
   CookieStore cookies = client.getCookieStore();
   if (cookies != null) {
     return !cookies.getCookies().isEmpty();
   }
   return false;
 }
  @Override
  public void activateBrowserfeatures(final Upload upload) throws UnirestException {

    // Create a local instance of cookie store
    // Populate cookies if needed
    final CookieStore cookieStore = new BasicCookieStore();
    for (final PersistentCookieStore.SerializableCookie serializableCookie :
        upload.getAccount().getSerializeableCookies()) {
      final BasicClientCookie cookie =
          new BasicClientCookie(
              serializableCookie.getCookie().getName(), serializableCookie.getCookie().getValue());
      cookie.setDomain(serializableCookie.getCookie().getDomain());
      cookieStore.addCookie(cookie);
    }

    final HttpClient client =
        HttpClientBuilder.create().useSystemProperties().setDefaultCookieStore(cookieStore).build();
    Unirest.setHttpClient(client);

    final HttpResponse<String> response =
        Unirest.get(String.format(VIDEO_EDIT_URL, upload.getVideoid())).asString();

    changeMetadata(response.getBody(), upload);

    final RequestConfig clientConfig =
        RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(600000).build();
    Unirest.setHttpClient(HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).build());
  }
 @Override
 public void process(HttpResponse response, HttpContext context)
     throws HttpException, IOException {
   CookieStore cookieStore = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
   for (Header header : response.getAllHeaders()) {
     if (!header.getName().equalsIgnoreCase("Set-Cookie")) {
       continue;
     }
     Matcher matcher = pattern.matcher(header.getValue());
     if (!matcher.find()) {
       continue;
     }
     for (Cookie cookie : cookieStore.getCookies()) {
       if (cookie.getName().equalsIgnoreCase(matcher.group(1))) {
         if (cookie instanceof BasicClientCookie) {
           ((BasicClientCookie) cookie).setValue('"' + cookie.getValue() + '"');
         } else if (cookie instanceof BasicClientCookie2) {
           ((BasicClientCookie2) cookie).setValue('"' + cookie.getValue() + '"');
         } else {
           Log.w(TAG, "unhandled cookie implementation " + cookie.getClass().getName());
         }
         break;
       }
     }
   }
 }
예제 #4
0
  private Response doRequest(final Request<?> request, final HttpRequestBase fetcher) {
    if (fetcher == null) {
      return null;
    }

    List<Parameter> headers = request.getHeaders();
    if (checkListOfParams(headers)) {
      for (Parameter parameter : headers) {
        Header header = new BasicHeader(parameter.getName(), parameter.getValue());
        fetcher.addHeader(header);
      }
    }

    final DefaultHttpClient httpClient = getHttpClient();
    List<Parameter> cookies = request.getCookies();
    if (checkListOfParams(cookies)) {
      CookieStore cookieStore = httpClient.getCookieStore();
      for (Parameter cookie : cookies) {
        cookieStore.addCookie(new BasicClientCookie(cookie.getName(), cookie.getValue()));
      }
      httpClient.setCookieStore(cookieStore);
    }

    return doRequest(fetcher, httpClient);
  }
예제 #5
0
  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
  }
예제 #6
0
 /**
  * 通过一个地址获取内容
  *
  * @param paramString
  * @throws UnsupportedEncodingException
  * @throws IllegalStateException
  * @throws ClientProtocolException
  * @throws IOException
  */
 public static String httpGet(String paramString)
     throws UnsupportedEncodingException, IllegalStateException, ClientProtocolException,
         IOException {
   HttpClient httpClient = getHttp();
   HttpUriRequest httpUriRequest = new HttpGet(paramString);
   BufferedReader bufferedReader =
       new BufferedReader(
           new InputStreamReader(
               (httpClient).execute(httpUriRequest).getEntity().getContent(), "UTF-8"));
   StringBuilder stringBuilder = new StringBuilder();
   String str = bufferedReader.readLine();
   CookieStore mCookieStore = ((AbstractHttpClient) httpClient).getCookieStore();
   List<org.apache.http.cookie.Cookie> cookies = mCookieStore.getCookies();
   for (int i = 0; i < cookies.size(); i++) {
     // 这里是读取Cookie['PHPSESSID']的值存在静态变量中,保证每次都是同一个值
     cookieStr = cookies.get(i).getName() + "=" + cookies.get(i).getValue();
   }
   if (str == null || str.equals("")) {
     stringBuilder.append(str);
     str = bufferedReader.readLine();
     return null;
   } else {
     return str;
   }
 }
예제 #7
0
 public boolean hasSession() {
   if (localContext != null) {
     CookieStore cookieStore = (CookieStore) localContext.getAttribute(ClientContext.COOKIE_STORE);
     if (cookieStore != null && cookieStore.getCookies() != null) {
       return true;
     }
   }
   return false;
 }
예제 #8
0
  @Test
  public void example3() {
    CookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("name", "value");
    cookieStore.addCookie(cookie);

    CloseableHttpClient httpClient =
        HttpClients.custom().setDefaultCookieStore(cookieStore).build();
  }
 private void clearAndAddPersistentCookies() {
   List<Cookie> cookies = new ArrayList<Cookie>(store.getCookies());
   store.clear();
   for (Cookie cookie : cookies) {
     if (cookie.isPersistent()) {
       store.addCookie(cookie);
     }
   }
 }
예제 #10
0
  private boolean isPurlRunning()
      throws URISyntaxException, HttpException, ClientProtocolException, IOException {

    DefaultHttpClient client = new DefaultHttpClient();

    URI url =
        new URI(
            "http://localhost:" + testInfo.getPurlzPort() + IdentifiersTestInfo.PURLZ_REST_LOGIN);
    HttpPost method = new HttpPost(url);

    List<NameValuePair> loginParams = new ArrayList<NameValuePair>();
    loginParams.add(new BasicNameValuePair("id", IdentifiersTestInfo.PURLZ_USER));
    loginParams.add(new BasicNameValuePair("passwd", IdentifiersTestInfo.PURLZ_PASSWORD));
    loginParams.add(new BasicNameValuePair("referrer", "/docs/index.html"));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(loginParams, "UTF-8");
    method.setEntity(entity);

    try {
      System.out.println("isPurlRunning connecting to " + url);
      HttpResponse response = client.execute(method);

      int statusCode = response.getStatusLine().getStatusCode();

      System.out.println("PURL Login: HTTP Status code: " + statusCode);

      if (statusCode != HttpStatus.SC_OK) {
        throw new HttpException(
            " [" + statusCode + ":" + response.getStatusLine().toString() + "]");
      }

      String responseStr = IdentifiersTestInfo.getResponseString(response);
      if (!responseStr.contains(IdentifiersTestInfo.PURLZ_WELCOME_MSG)) {
        System.out.println("BAD RESPONSE FROM SERVER [" + responseStr + "]");
        return false;
      }

      System.out.println("Login to PURL successful...");

      CookieStore store = client.getCookieStore();

      for (Cookie cookie : store.getCookies()) {
        if (cookie.getName().equalsIgnoreCase(IdentifiersTestInfo.PURLZ_LOGIN_COOKIE)) {
          testInfo.setPurlzLoginCookie(cookie);
          return true;
        }
      }
    } finally {
      // Release the connection.
      method.abort();
      client.getConnectionManager().shutdown();
    }

    return false;
  }
예제 #11
0
 /** Debug method to print cookies */
 public void printCookies() {
   if (localContext != null) {
     CookieStore cookieStore = (CookieStore) localContext.getAttribute(ClientContext.COOKIE_STORE);
     if (cookieStore != null) {
       for (Cookie cookie : cookieStore.getCookies()) {
         Log.i(tag, "printCookie() >> current cookie is ============= " + cookie.getValue());
       }
     }
   }
   Log.i(tag, "printCookie() >> current cookie is empty============= ");
 }
  private static CookieStore handleCsrfCookies(CookieStore cookieStore) {
    List<Cookie> cookies = new ArrayList<Cookie>();
    for (Cookie cookie : cookieStore.getCookies()) {
      if (!cookie.getName().contains("CSRF")) {
        cookies.add(cookie);
      }
    }

    cookieStore.clear();

    for (Cookie cookie : cookies) {
      cookieStore.addCookie(cookie);
    }
    return cookieStore;
  }
예제 #13
0
 public void handleMessage(android.os.Message msg) {
   DefaultHttpClient httpClient;
   httpClient = (DefaultHttpClient) httpRequest.getHttpClient();
   CookieStore mCookieStore = httpClient.getCookieStore();
   List<Cookie> cookies = mCookieStore.getCookies();
   String PHPSESSID = null;
   for (int i = 0; i < cookies.size(); i++) {
     // 这里是读取Cookie['PHPSESSID']的值存在静态变量中,保证每次都是同一个值
     if ("PHPSESSID".equals(cookies.get(i).getName())) {
       PHPSESSID = cookies.get(i).getValue();
       userShare.SaveSession(PHPSESSID);
       Log.e("PHPSESSID", PHPSESSID + "");
       break;
     }
   }
 };
예제 #14
0
 @Implementation
 public void setCookie(String url, String value) {
   List<Cookie> cookies = parseCookies(url, value);
   for (Cookie cookie : cookies) {
     store.addCookie(cookie);
   }
 }
예제 #15
0
파일: HttpClient.java 프로젝트: hlf/WebQQ
 public String connectByPost(String url) {
   HttpPost httpPost = new HttpPost(url);
   System.out.println(url);
   try {
     // httpPost.addHeader("Referer",
     // "https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=5&mibao_css=m_webqq&appid=1003903&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=20131202001");
     List<Cookie> cookies = cookieStore.getCookies();
     for (Cookie cookie : cookies) {
       if (cookie.getName().equals("ptwebqq")) {
         this.ptWebqq = cookie.getValue();
       }
     }
     System.out.println(ptWebqq);
     httpPost.addHeader("clientid", "48847830");
     httpPost.addHeader("psessionid", "null");
     httpPost.addHeader(
         "r",
         "{\"status\":\"online\",\"ptwebqq\":\""
             + this.ptWebqq
             + "\",\"passwd_sig\":\"\",\"clientid\":\"48847830\",\"psessionid\":null}");
     CloseableHttpResponse response = this.httpClient.execute(httpPost);
     HttpEntity entity = response.getEntity();
     this.getContent = EntityUtils.toString(entity);
     response.close();
     httpPost.abort();
   } catch (Exception e) {
     // TODO 自动生成的 catch 块
     e.printStackTrace();
   } finally {
     return getContent;
   }
 }
예제 #16
0
  public static void login(Map<String, String> connConf, String userName, String pwd) {
    String checkImgPage =
        "https://webim.feixin.10086.cn/WebIM/GetPicCode.aspx?Type=ccpsession&0.6949566061972312";
    String check = getChkImage(checkImgPage);
    connConf.put("check", check);

    String loginUrl = "https://webim.feixin.10086.cn/WebIM/Login.aspx";

    Map<String, String> postData = new HashMap<String, String>();
    postData.put("Ccp", check);
    postData.put("OnlineStatus", "400");
    postData.put("Pwd", pwd);
    postData.put("UserName", userName);

    postText(loginUrl, postData);

    String ssid = null;
    CookieStore cookieStroe = getCookieStroe();
    List<Cookie> cookies = cookieStroe.getCookies();
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals("webim_sessionid")) {
        ssid = cookie.getValue();
        connConf.put("ssid", ssid);
        log.debug("webim_sessionid:" + ssid);
      }
    }

    String preQueryUidUrl =
        "https://webim.feixin.10086.cn/content/WebIM/GetPicCode.aspx?Type=addbuddy_ccpsession&0.7922769554654019";
    getText(preQueryUidUrl);
    String ccpId = null;
    String ccpsession = null;
    cookies = cookieStroe.getCookies();
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals("addbuddy_ccpsession")) {
        ccpId = cookie.getValue();
        connConf.put("ccpId", ccpId);
        // cookies.remove(cookie);
        log.debug("addbuddy_ccpsession:" + ccpId);
      }
      if (cookie.getName().equals("ccpsession")) {
        ccpsession = cookie.getValue();
        // cookies.remove(cookie);
        log.debug("ccpsession:" + ccpsession);
      }
    }
  }
  private void loadCookiesFromPreferences(Context context, DefaultHttpClient client) {
    final CookieStore cookieStore = client.getCookieStore();
    final SharedPreferences sharedPreferences =
        context.getSharedPreferences(SHARED_PREFERENCES_NAME_SUMC_COOKIES, Context.MODE_PRIVATE);

    int i = 0;
    while (sharedPreferences.contains(PREFERENCES_COOKIE_NAME + i)) {
      final String name = sharedPreferences.getString(PREFERENCES_COOKIE_NAME + i, null);
      final String value = sharedPreferences.getString(PREFERENCES_COOKIE_VALUE + i, null);
      final BasicClientCookie result = new BasicClientCookie(name, value);

      result.setDomain(sharedPreferences.getString(PREFERENCES_COOKIE_DOMAIN + i, null));
      result.setPath(sharedPreferences.getString(PREFERENCES_COOKIE_PATH + i, null));
      cookieStore.addCookie(result);
      i++;
    }
  }
예제 #18
0
 private void getCookieFromTr1(MyRespone myRespone) {
   Header[] headers = myRespone.getHttpClientContext().getResponse().getHeaders("Set-Cookie");
   for (Header header : headers) {
     BasicClientCookie cookie =
         new BasicClientCookie(
             header.getValue().split(";")[0].split("=")[0],
             header.getValue().split(";")[0].split("=")[1]);
     cookie.setDomain(host);
     cookie.setPath("/");
     cookieStore.addCookie(cookie);
     System.out.println(header.getValue().split(";")[0].split("=")[1]);
   }
   BasicClientCookie cookie = new BasicClientCookie("PLUS", "1");
   cookie.setDomain(host);
   cookie.setPath("/");
   cookieStore.addCookie(cookie);
 }
예제 #19
0
  /**
   * @author Owater
   * @createtime 2015-1-14 上午12:23:06 @Decription 登录和再次登录
   * @param params
   * @param url
   * @return
   */
  public static String login(
      Context context, List<NameValuePair> params, String url, String jdycode) {
    String result = "";
    if (!isNetworkConnected(context)) {
      return Constants.NOT_NET + "";
    }
    try {
      HttpPost httpRequest = new HttpPost(url);
      if (params != null) {
        HttpEntity httpEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
        httpRequest.setEntity(httpEntity);
      }

      DefaultHttpClient httpClient = getHttpClient();
      httpClient.getParams().setParameter("http.socket.timeout", new Integer(30000));
      if (JSESSIONID != null && jdycode != null) {
        httpRequest.setHeader("Cookie", "JSESSIONID=" + JSESSIONID);
      }
      HttpResponse httpResponse = httpClient.execute(httpRequest);
      if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        result = EntityUtils.toString(httpResponse.getEntity());
        CookieStore mCookieStore = httpClient.getCookieStore();
        List<Cookie> cookies = mCookieStore.getCookies();
        // 读取服务器返回的cookie
        for (int i = 0; i < cookies.size(); i++) {
          String cookieName = cookies.get(i).getName();
          if ("JSESSIONID".equals(cookieName)) {
            JSESSIONID = cookies.get(i).getValue();
            break;
          }
        }
        Log.i("commit", "提交成功");
      } else {
        result = Constants.GETFALL + "";
        Log.i("commit", "提交失败");
      }
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }
예제 #20
0
  public static void showClient(BaseClient client, CookieStore cookieStore) {
    showClient(client);

    System.out.println("-------------------------------------------------------");
    System.out.println("COOKIES:");
    System.out.println("-------------------------------------------------------");
    System.out.println(cookieStore.getCookies());
    System.out.println("");
  }
예제 #21
0
 private void generateCookie(HttpClientBuilder httpClientBuilder, Site site) {
   CookieStore cookieStore = new BasicCookieStore();
   for (Map.Entry<String, String> cookieEntry : site.getCookies().entrySet()) {
     BasicClientCookie cookie =
         new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
     cookie.setDomain(site.getDomain());
     cookieStore.addCookie(cookie);
   }
   for (Map.Entry<String, Map<String, String>> domainEntry : site.getAllCookies().entrySet()) {
     for (Map.Entry<String, String> cookieEntry : domainEntry.getValue().entrySet()) {
       BasicClientCookie cookie =
           new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
       cookie.setDomain(domainEntry.getKey());
       cookieStore.addCookie(cookie);
     }
   }
   httpClientBuilder.setDefaultCookieStore(cookieStore);
 }
예제 #22
0
  @Override
  public void retrieve() throws RetrieverException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient
        .getParams()
        .setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    HttpContext context = new BasicHttpContext();

    accounts = new HashMap<String, Account>();
    try {
      CookieStore cookieStore = httpClient.getCookieStore();
      BasicClientCookie newCookie = new BasicClientCookie("XPRDMBP1E", registrationCookie);
      newCookie.setVersion(0);
      newCookie.setDomain("bankservices.rabobank.nl");
      newCookie.setPath("/");
      cookieStore.addCookie(newCookie);

      if (!checkAppStatus(httpClient, context)) {
        throw new RetrieverException("Application status is not OK");
      }

      if (!loginWithAccessCode(httpClient, context, accountNumber, accessCode)) {
        throw new RetrieverException("Login with access code failed", true);
      }

      List<Account> accountList = retrieveAccounts(httpClient, context);

      logoff(httpClient, context);

      accounts = new HashMap<String, Account>();
      for (Account account : accountList) {
        accounts.put(account.getAccountName(), account);
      }

      for (Cookie cookie : httpClient.getCookieStore().getCookies()) {
        if ("XPRDMBP1E".equals(cookie.getName())) {
          registrationCookie = cookie.getValue();
        }
      }
    } catch (IOException e) {
      throw new RetrieverException(e);
    }
  }
예제 #23
0
 /**
  * 传递参数的数据请求
  *
  * @param paramString
  * @param paramList
  * @return
  * @throws ClientProtocolException
  * @throws IOException
  * @throws JSONException
  */
 public static String httpPost(String paramString, List<NameValuePair> paramList)
     throws ClientProtocolException, IOException {
   HttpClient defaultHttpClient = getHttp();
   HttpUriRequest httpPost = new HttpPost(paramString);
   if (null != paramList)
     ((HttpEntityEnclosingRequestBase) httpPost)
         .setEntity(
             new UrlEncodedFormEntity(
                 (java.util.List<? extends org.apache.http.NameValuePair>) paramList, "UTF-8"));
   HttpEntity httpEntity = defaultHttpClient.execute(httpPost).getEntity();
   if (httpEntity == null) return null;
   String resultStr = EntityUtils.toString(httpEntity);
   CookieStore mCookieStore = ((AbstractHttpClient) defaultHttpClient).getCookieStore();
   List<org.apache.http.cookie.Cookie> cookies = mCookieStore.getCookies();
   for (int i = 0; i < cookies.size(); i++) {
     // 这里是读取Cookie['PHPSESSID']的值存在静态变量中,保证每次都是同一个值
     cookieStr = cookies.get(i).getName() + "=" + cookies.get(i).getValue();
   }
   return resultStr;
 }
예제 #24
0
  private static int getContacktJsonList(String ssid, CookieStore cookieStroe, int version) {
    String getContactListUrl =
        "https://webim.feixin.10086.cn/WebIM/GetContactList.aspx?Version=" + version++;
    Map<String, String> postData = new HashMap<String, String>();
    postData.put("ssid", ssid);

    BasicClientCookie cookie = new BasicClientCookie("IsCookiesEnable", "true");
    cookie.setVersion(0);
    cookie.setDomain(".webim.feixin.10086.cn");
    cookie.setPath("/");
    cookieStroe.addCookie(cookie);

    cookie = new BasicClientCookie("webim_login_status", "0");
    cookie.setVersion(0);
    cookie.setDomain(".webim.feixin.10086.cn");
    cookie.setPath("/");
    cookieStroe.addCookie(cookie);

    cookie = new BasicClientCookie("webim_loginCounter", "1342244257406");
    cookie.setVersion(0);
    cookie.setDomain(".webim.feixin.10086.cn");
    cookie.setPath("/");
    cookieStroe.addCookie(cookie);

    cookie =
        new BasicClientCookie(
            "webim_remindmsgs", "645048052-39532%21191-0-a56dcfc5f2c943adb168c91f6456fe59");
    cookie.setVersion(0);
    cookie.setDomain(".feixin.10086.cn");
    cookie.setPath("/");
    cookieStroe.addCookie(cookie);

    // {"rc":521,"rv":{"bl":"0","bss":1,"ln":"","rs":0,"uid":223534907,"uri":"tel:13636532333","v":"0"}}
    // JSONObject json = postTextToJson(getContactListUrl, postData);
    // String uid = null;
    // if(json.getString("rc").equals("521")){
    // uid = json.getJSONObject("rv").getString("uid");
    // log.debug("uid:" + uid);
    // }
    return version;
  }
예제 #25
0
  public static void main(String[] args) {
    BasicClientCookie cookie = new BasicClientCookie("test", "test");
    cookie.setDomain("115.159.3.51");
    cookie.setPath("/");
    CookieStore cs = new BasicCookieStore();
    cs.addCookie(cookie);
    System.out.println(cs.getCookies());
    try {
      CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cs).build();
      HttpGet httpGet = new HttpGet("http://115.159.3.51/cookieShow.php");
      CloseableHttpResponse response = httpClient.execute(httpGet);
      try {
        HttpEntity responseEntity = response.getEntity();
        System.out.println(EntityUtils.toString(responseEntity));

      } finally {
        response.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #26
0
 private List<Cookie> filter(CookieOrigin origin) {
   List<Cookie> matchedCookies = new ArrayList<Cookie>();
   Date now = new Date();
   CookieSpec cookieSpec = createSpec();
   for (Cookie cookie : store.getCookies()) {
     if (!cookie.isExpired(now)) {
       if (cookieSpec.match(cookie, origin)) {
         matchedCookies.add(cookie);
       }
     }
   }
   return matchedCookies;
 }
예제 #27
0
 /**
  * Проверяет авторизирован ли пользователь,удаляет все куки записи которые неявляются
  * обязательными
  *
  * @return true если авторизирован
  */
 public boolean isAutorizted() {
   List<Cookie> listCookie = new ArrayList<Cookie>();
   // System.out.println(cookie.getCookies().size());
   for (Cookie cookieElement : cookie.getCookies()) {
     boolean result = false;
     for (String mandatoryEl : mandatoryElements)
       if (cookieElement.getName().compareTo(mandatoryEl) == 0) {
         result = true;
         break;
       }
     if (result) {
       listCookie.add(cookieElement);
     }
   }
   cookie.clear();
   // System.out.println(cookie.getCookies().size());
   for (Cookie cookieElement : listCookie) {
     cookie.addCookie(cookieElement);
   }
   // System.out.println(cookie.getCookies().size());
   return cookie.getCookies().size() == mandatoryElements.length;
 }
예제 #28
0
  /**
   * android中HttpClient和WebView共享session的解决办法
   *
   * <p>android开始项目中,通常会遇到既使用HttpClient,又使用WebView的情况。一个典型的例子是,使用HttpClient登录,WebView展示登录后的某些页面,这个时候,如果直接不加任何处理的话会发现在使用WebView展示的时候,会提示没有登录你的应用系统,造成这种结果的原因就是使用HttpClient登录的session和WebView访问服务器的session并不是同一个,解决办法如下。
   * WebView代码
   *
   * @param url4load
   */
  protected void session(String url4load) {
    // String url4load = "登录域名下你要访问的地址";
    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    //		Cookie sessionCookie = HttpStreamThread.sessionCookie;//this.sessionCookie;
    //		if (sessionCookie != null) {
    //			String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + ";
    // domain=" + sessionCookie.getDomain();
    //			cookieManager.setCookie(url4load, cookieString);
    //			CookieSyncManager.getInstance().sync();
    //		}

    CookieStore cookieStore = HttpStreamThread.cookieStore;
    if (null != cookieStore) {
      List<Cookie> cookies = cookieStore.getCookies();
      StringBuilder sb = new StringBuilder();
      if (null != cookies) {
        for (int i = 0; i < cookies.size(); i++) {
          // 这里是读取Cookie['PHPSESSID']的值存在静态变量中,保证每次都是同一个值
          //                if (cookie_key.equals(cookies.get(i).getName())) {
          //                	cookie_value = cookies.get(i).getValue();
          //                	sessionCookie = cookies.get(i);
          //                }
          sb.append(
              cookies.get(i).getName()
                  + "="
                  + cookies.get(i).getValue()
                  + "; domain="
                  + cookies.get(i).getDomain()
                  + " ");
        }
      }

      cookieManager.setCookie(url4load, sb.toString());
      CookieSyncManager.getInstance().sync();
    }
  }
예제 #29
0
 /**
  * HttpClient 登录代码如下
  *
  * @param url
  * @throws Exception
  */
 private void login(String url) throws Exception {
   //		HttpClient 登录代码如下
   DefaultHttpClient client = new DefaultHttpClient();
   HttpGet get = new HttpGet(url);
   HttpContext context = new BasicHttpContext();
   CookieStore cookieStore = new BasicCookieStore();
   context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
   HttpResponse response = client.execute(get, context);
   if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
     // 根据你的逻辑,判断返回的值是不是表示已经登录成功
     //			if (isLoginSuccess()) {
     List<Cookie> cookies = cookieStore.getCookies();
     if (!cookies.isEmpty()) {
       for (int i = cookies.size(); i > 0; i--) {
         Cookie cookie = cookies.get(i - 1);
         if (cookie.getName().equalsIgnoreCase(PHPSESSID)) { // "jsessionid"
           // 使用一个常量来保存这个cookie,用于做session共享之用
           sessionCookie = cookie;
         }
       }
     }
     //			}
   }
 }
예제 #30
0
 private void getCookieFromHome(MyRespone myRespone) {
   Header[] headers = myRespone.getHttpClientContext().getResponse().getHeaders("Set-Cookie");
   for (Header header : headers) {
     if (!header.getValue().contains("__bsi")) {
       BasicClientCookie cookie =
           new BasicClientCookie(
               header.getValue().split(";")[0].split("=")[0],
               header.getValue().split(";")[0].split("=")[1]);
       cookie.setDomain(host);
       cookie.setPath("/");
       //				System.out.println(cookie);
       cookieStore.addCookie(cookie);
     }
   }
 }