Beispiel #1
0
 @Test
 public void testResponse() throws Exception {
   WebClient webClient = new WebClient();
   TextPage page = webClient.getPage(url);
   assertEquals("Pong", page.getContent());
   webClient.closeAllWindows();
 }
Beispiel #2
0
  public boolean athenticated() {

    web = new WebClient();
    try {
      page1 = web.getPage(url);
    } catch (FailingHttpStatusCodeException | IOException e) {
      e.printStackTrace();
    }
    HtmlForm form = page1.getFormByName("form2");

    form.getInputByName("txtUserName").setAttribute("value", username);
    form.getInputByName("txtPassword").setAttribute("value", password);
    try {
      page2 = form.getInputByName("LoginButton").click();
    } catch (ElementNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    if (page2.getUrl().toString().equals("http://78.39.200.210/Default.aspx")) {
      return true;
    } else {
      web.closeAllWindows();
      return false;
    }
  }
Beispiel #3
0
  public static void main(String[] args) throws Exception {

    //    	WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24, "54.186.230.121", 3128);
    WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24);

    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.setJavaScriptTimeout(10000);
    webClient.getOptions().setJavaScriptEnabled(true);
    webClient.setAjaxController(new NicelyResynchronizingAjaxController());
    webClient.getOptions().setTimeout(10000);

    //    	webClient.getOptions().setJavaScriptEnabled(false);
    //		webClient.getOptions().setAppletEnabled(false);
    //		webClient.getOptions().setCssEnabled(false);

    //		webClient.getOptions().setThrowExceptionOnScriptError(false);
    //		webClient.setJavaScriptTimeout(10000);
    //		webClient.getOptions().setJavaScriptEnabled(true);
    //		webClient.setAjaxController(new NicelyResynchronizingAjaxController());
    //		webClient.getOptions().setTimeout(10000);

    //		webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
    //		webClient.getOptions().setThrowExceptionOnScriptError(false);

    HtmlPage currentPage = webClient.getPage("http://www.yandex.ru/");
    //    	HtmlPage currentPage = webClient.getPage("http://www.google.ru");

    //    	HtmlDivision div = currentPage.getHtmlElementById("del_competitors-1_42");

    //    	HtmlElement clickable = (HtmlElement)
    // currentPage.getHtmlElementById("del_competitors-1_42");
    //    	currentPage = (HtmlPage) clickable.click();

    HtmlAnchor advancedSearchAn = currentPage.getAnchorByText("Завести ящик");
    currentPage = advancedSearchAn.click();

    HtmlImage image = currentPage.<HtmlImage>getFirstByXPath("//img[@src='images/ash2008.jpg']");
    currentPage = (HtmlPage) image.click();

    System.out.println(currentPage.asXml());

    //    	HtmlImage image =
    // currentPage.<HtmlImage>getFirstByXPath("//img[@src='images/ash2008.jpg']");
    //    	currentPage = (HtmlPage) image.click();

    //    	HtmlImage imagetosave =
    // currentPage.<HtmlImage>getFirstByXPath("//img[@src='//yastatic.net/www/1.977/yaru/i/logo.png']");

    //    	HtmlImage image = currentPage.<HtmlImage>getHtmlElementById("add_competitors-1_3");
    //    	currentPage = (HtmlPage) image.click();

    //    	File imageFile = new File("test_new.jpg");
    //    	image.saveAs(imageFile);

    //    	System.out.println(currentPage.asXml());

    System.out.println("It is done.");

    webClient.closeAllWindows();
  }
 /**
  * Test method.
  *
  * @throws IOException exception
  */
 public void testLogin() throws IOException {
   final WebClient webClient = new WebClient();
   // XXX: issues with jquery
   webClient.setJavaScriptEnabled(false);
   final HtmlPage page = webClient.getPage(HTTP_PROCC_LOGIN_USER);
   assertEquals("Taskflow-Logowanie", page.getTitleText());
   webClient.closeAllWindows();
 }
 public static void main(String[] args) throws Exception {
   HtmlPage page;
   final WebClient webClient = new WebClient();
   String url = "http://www.google.com";
   if (args.length >= 1) url = args[0];
   /*
   webClient.setJavaScriptEnabled(false);
   */
   page = webClient.getPage(url);
   System.out.println(page.asXml());
   webClient.closeAllWindows();
 }
  @Test
  public void testSimple2() throws IOException {
    System.out.println("Hello");
    final WebClient webClient = new WebClient(BrowserVersion.CHROME);

    final LinkedList<String> traces = new LinkedList<String>();
    webClient
        .getWebConsole()
        .setLogger(
            new WebConsole.Logger() {
              @Override
              public void trace(Object o) {
                traces.add(o.toString());
                System.out.println(o);
              }

              @Override
              public void debug(Object o) {
                traces.add(o.toString());
                System.out.println(o);
              }

              @Override
              public void info(Object o) {
                traces.add(o.toString());
                System.out.println(o);
              }

              @Override
              public void warn(Object o) {
                traces.add(o.toString());
                System.out.println(o);
              }

              @Override
              public void error(Object o) {
                traces.add(o.toString());
                System.out.println(o);
              }
            });

    File html = new File("tester2.html");
    final HtmlPage page = webClient.getPage("file:///" + html.getAbsolutePath());

    assert (traces.get(0).toLowerCase().contains("add event"));
    assert (traces.get(1).toLowerCase().contains("set event"));
    assert (traces.get(2).toLowerCase().contains("renewindex"));
    assertEquals(traces.get(3), "model1=helloRename");
    assertEquals(traces.get(4), "model2=helloRename");

    webClient.closeAllWindows();
  }
Beispiel #7
0
  /**
   * Static method for <code>Login</code>. Uses dependencies <b>HttpUnit</b> in connecting to Keats.
   *
   * @see com.gargoylesoftware.htmlunit
   * @param parent The parent window. instanceof<code>Scrape</code>, to set relative locations to
   * @param link The url of which to retrieve information from.
   * @param username The username to log in KEATS with.
   * @param password The password to log in KEATS with.
   * @return results.asText() Returns the content of the url if login successful. Returns null
   *     otherwise.
   */
  public static String login(Scrape parent, String link, String username, String password) {
    try {
      WebClient client = new WebClient();

      // Settings
      client.getOptions().setThrowExceptionOnScriptError(false);
      client.getOptions().setThrowExceptionOnScriptError(false);
      client.getOptions().setThrowExceptionOnFailingStatusCode(false);
      client.getOptions().setJavaScriptEnabled(false);
      client.getOptions().setCssEnabled(false);
      client.getOptions().setRedirectEnabled(true);
      client.getOptions().setUseInsecureSSL(true);
      client.getCookieManager().setCookiesEnabled(true);

      HtmlPage page = client.getPage("https://login-keats.kcl.ac.uk/");

      HtmlForm form =
          page.getFirstByXPath("//form[@action='https://keats.kcl.ac.uk/login/index.php']");

      HtmlInput usernameInput = form.getInputByName("username");
      usernameInput.setValueAttribute(username);
      HtmlInput passwordInput = form.getInputByName("password");
      passwordInput.setValueAttribute(password);

      page = form.getInputByValue("Log in").click();

      HtmlPage results = client.getPage(link);

      client.closeAllWindows();
      return results.asText();
    } catch (MalformedURLException e) {
      JOptionPane.showMessageDialog(
          parent,
          "The URL you have provided is not recognised. Please double check your "
              + "input and try again.",
          "MalformedURLException found.",
          JOptionPane.ERROR_MESSAGE);
      e.printStackTrace();
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          parent,
          "An error has occurred when attempting to read information from the "
              + "server. The input could be interrupted by external processes.",
          "IOException found.",
          JOptionPane.ERROR_MESSAGE);
      e.printStackTrace();
    }

    return null;
  }
Beispiel #8
0
  private void search(SearchEngine se) {
    try {

      initializeJdbc();
      final WebClient webClient =
          new WebClient(
              getBrowserVersionFromName(se.getDefaultBrowser())); // BrowserVersion.FIREFOX_24);
      // webClient.getOptions().setThrowExceptionOnScriptError(false);
      String htmlSource;
      HtmlPage searchResultPage = null;
      //            String baseUrl = url;

      int numberOfUrlsExtracted;
      searchResultPage = clickSearchButtonMainPage(webClient, se);
      htmlSource = searchResultPage.getWebResponse().getContentAsString();

      numberOfUrlsExtracted =
          ExtractAndInsertSeedUrls(searchResultPage, htmlSource, 1, 0, se.getName());
      target.dispatchEvent(new EventSearchWorker(target, 1));

      try {
        for (int i = 1; i < maxPage; i++) {
          HtmlAnchor ha =
              (HtmlAnchor) getNextButtonOrLink(searchResultPage, se.getNextButtonIdentifier());

          searchResultPage = ha.click();
          htmlSource = searchResultPage.getWebResponse().getContentAsString();
          numberOfUrlsExtracted =
              ExtractAndInsertSeedUrls(
                  searchResultPage, htmlSource, i + 1, numberOfUrlsExtracted, se.getName());
          // nextUrl = getNextUrl(b, se, baseUrl);
          target.dispatchEvent(new EventSearchWorker(target, 1));

          Random r = new Random();
          int randomSleepTime = r.nextInt(2000) + 200; // minimum 200 ms max 2200 ms
          Thread.sleep(randomSleepTime);
        }
        // fw.close();
      } catch (Exception ex) {
        String x = ex.getMessage();
      }
      webClient.closeAllWindows();
    } catch (Exception ex) {
      String x = ex.getMessage();
    }
  }
 /**
  * Test cm server.
  *
  * @throws FailingHttpStatusCodeException the failing http status code exception
  * @throws MalformedURLException the malformed url exception
  * @throws IOException Signals that an I/O exception has occurred.
  */
 @Test
 public void testCMServer()
     throws FailingHttpStatusCodeException, MalformedURLException, IOException {
   final Properties settings = new Properties();
   settings.load(ApplicationStartupTest.class.getResourceAsStream("/test.properties"));
   final WebClient webClient = new WebClient();
   final Page page =
       webClient.getPage(
           "http://localhost:"
               + settings.getProperty("cargo.port")
               + settings.getProperty("cmserver.context")
               + "/diagnostics.ep");
   assertEquals(HTTP_STATUS_OK, page.getWebResponse().getStatusCode());
   assertTrue(page instanceof TextPage);
   TextPage textPage = (TextPage) page;
   assertEquals("I am alive!", textPage.getContent());
   webClient.closeAllWindows();
 }
 /**
  * Test search server.
  *
  * @throws FailingHttpStatusCodeException the failing http status code exception
  * @throws MalformedURLException the malformed url exception
  * @throws IOException Signals that an I/O exception has occurred.
  */
 @Test
 public void testSearchServer()
     throws FailingHttpStatusCodeException, MalformedURLException, IOException {
   final Properties settings = new Properties();
   settings.load(ApplicationStartupTest.class.getResourceAsStream("/test.properties"));
   final WebClient webClient = new WebClient();
   final Page page =
       webClient.getPage(
           "http://localhost:"
               + settings.getProperty("cargo.port")
               + settings.getProperty("search.context")
               + "/product/select?q=*:*");
   assertEquals(HTTP_STATUS_OK, page.getWebResponse().getStatusCode());
   assertTrue(page instanceof XmlPage);
   XmlPage xmlPage = (XmlPage) page;
   assertTrue(xmlPage.hasChildNodes());
   webClient.closeAllWindows();
 }
Beispiel #11
0
  /**
   * Test method.
   *
   * @throws IOException exception
   */
  public void testLoginValid() throws IOException {
    final WebClient webClient = new WebClient();
    // XXX: issues with jquery
    webClient.setJavaScriptEnabled(false);
    final HtmlPage page = webClient.getPage(HTTP_PROCC_LOGIN_USER);
    final HtmlForm form = page.getFormByName(LOGIN_USER_FORM_NAME);

    final HtmlTextInput textEmail = form.getInputByName(EMAIL_INPUT_NAME);
    final HtmlPasswordInput textPassword = form.getInputByName(PASSWD_INPUT_NAME);
    final HtmlSubmitInput btnLogin = form.getInputByName(LOGIN_SUBMIT_NAME);

    textEmail.setValueAttribute("*****@*****.**");
    textPassword.setValueAttribute("malczyk123");

    final HtmlPage nextPage = btnLogin.click();
    assertTrue(nextPage.getTitleText().equals("Taskflow-Main"));

    webClient.closeAllWindows();
  }
Beispiel #12
0
  /**
   * Test method.
   *
   * @throws IOException exception
   */
  public void testLoginInvalid() throws IOException {
    final WebClient webClient = new WebClient();
    // XXX: issues with jquery
    webClient.setJavaScriptEnabled(false);
    final HtmlPage page = webClient.getPage(HTTP_PROCC_LOGIN_USER);
    final HtmlForm form = page.getFormByName(LOGIN_USER_FORM_NAME);

    final HtmlTextInput textEmail = form.getInputByName(EMAIL_INPUT_NAME);
    final HtmlPasswordInput textPassword = form.getInputByName(PASSWD_INPUT_NAME);
    final HtmlSubmitInput btnLogin = form.getInputByName(LOGIN_SUBMIT_NAME);

    textEmail.setValueAttribute("invalidLogin");
    textPassword.setValueAttribute("invalidPasswd");

    final HtmlPage nextPage = btnLogin.click();
    assertTrue(nextPage.asText().contains("Błędny login bądź hasło"));

    webClient.closeAllWindows();
  }
  private void ProcessTest(WebTest test) {
    HtmlPage page = null;

    // Orville.LOG().info(String.format("Executing test %s\n", event));

    WebClient webClient = new WebClient();
    webClient.setRefreshHandler(new ThreadedRefreshHandler());
    webClient.getOptions().setJavaScriptEnabled(false);

    try {
      if (test.getMethod().toLowerCase().equals("post")) {
        WebRequest request =
            new WebRequest(UrlUtils.toUrlUnsafe(test.getUrlString()), HttpMethod.POST);

        request.setRequestParameters(new ArrayList<NameValuePair>());

        for (Map.Entry<String, String> entry : test.getPostData().entrySet()) {
          request.getRequestParameters().add(new NameValuePair(entry.getKey(), entry.getValue()));
        }

        page = webClient.getPage(request);
      } else {
        page = webClient.getPage(test.getUrlString());
      }

      ProcessResult(test, page.getWebResponse());

    } catch (FailingHttpStatusCodeException fsc) {
      Orville.LOG()
          .warning(
              String.format(
                  "Failing HTTP Status code caught executing the test command: %s\n",
                  fsc.getMessage()));
    } catch (IOException ioe) {
      Orville.LOG()
          .warning(
              String.format(
                  "IO Exception caught executing the test command: %s\n", ioe.getMessage()));
    }

    webClient.closeAllWindows();
  }
 /**
  * Test storefront.
  *
  * @throws FailingHttpStatusCodeException the failing http status code exception
  * @throws MalformedURLException the malformed url exception
  * @throws IOException Signals that an I/O exception has occurred.
  */
 @Test
 public void testStorefront()
     throws FailingHttpStatusCodeException, MalformedURLException, IOException {
   final Properties settings = new Properties();
   settings.load(ApplicationStartupTest.class.getResourceAsStream("/test.properties"));
   final WebClient webClient = new WebClient();
   // use the store code to get to the storefront
   final Page page =
       webClient.getPage(
           "http://localhost:"
               + settings.getProperty("cargo.port")
               + settings.getProperty("storefront.context")
               + "?storeCode="
               + settings.getProperty("store.code"));
   assertEquals(HTTP_STATUS_OK, page.getWebResponse().getStatusCode());
   assertTrue(page instanceof HtmlPage);
   HtmlPage htmlPage = (HtmlPage) page;
   assertTrue(htmlPage.getTitleText().length() != 0);
   webClient.closeAllWindows();
 }
Beispiel #15
0
 @After
 public void tearDown() {
   webClient.closeAllWindows();
 }
Beispiel #16
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    int no = 0;
    try {
      no = Integer.parseInt(request.getParameter("no"));

    } catch (NumberFormatException exception) {
      no = 0;
    }

    try {
      /* TODO output your page here. You may use following sample code. */
      out.println("<!DOCTYPE html>");
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet NewServlet</title>");
      out.println("</head>");
      out.println("<body>");

      final WebClient webClient = new WebClient();
      webClient.getCookieManager().clearCookies();
      webClient.getOptions().setUseInsecureSSL(true);
      webClient.setJavaScriptEnabled(false);
      final HtmlPage page = webClient.getPage("https://filestream.me/");
      // out.println(page.getTitleText());
      System.out.println("no of forms : " + page.getForms().size());
      HtmlForm form = page.getForms().get(1);
      final HtmlTextInput textField = form.getInputByName("login");
      textField.setAttribute("value", "*****@*****.**");

      final HtmlPasswordInput passField = form.getInputByName("password");
      passField.setAttribute("value", "ramkrishnan18");
      HtmlSubmitInput htmlSubmitInput = form.getInputByValue("login");
      HtmlPage page1 = htmlSubmitInput.click();

      HtmlTable htmlTable = page1.getHtmlElementById("fileCatTable");
      List<HtmlTableRow> listOfHtmlTableRow = htmlTable.getBodies().get(0).getRows();
      List<String> allLinks = new ArrayList<String>();
      for (HtmlTableRow htmlTableRow : listOfHtmlTableRow) {
        HtmlTableCell cell = htmlTableRow.getCells().get(htmlTableRow.getCells().size() - 1);
        for (DomElement domElement : cell.getChildElements()) {
          // out.println(domElement.getTagName());
          if (domElement.getTagName().equals("div")) {
            boolean flag = true;

            for (DomElement celldomElement : domElement.getChildElements()) {
              if (flag) {
                // out.println(celldomElement.getTagName());

                String title = celldomElement.getAttribute("title");
                if ("Download".equals(title) || "Downloads".equals(title)) {

                  String link = celldomElement.getAttribute("onclick");
                  String http =
                      link.substring(
                          link.indexOf('\'') + 1, link.indexOf('\'', link.indexOf('\'') + 1));

                  //  out.println(celldomElement.getAttribute("onclick") + "<br/>");
                  // out.println(http + "<br/>");
                  allLinks.add(http);
                  flag = false;
                }
              }
            }
          }
        }
      }

      //  InputStream is =anchorAttachment.click().getWebResponse().getContentAsStream();

      out.println("************ Start *************");

      //  HtmlAnchor anchorElement=HTMLAnchorElement.;
      //  anchorElement.set
      // anchorElement.setHref(allLinks.get(0));

      //  anchorElement.cl
      final String u = allLinks.get(no);
      Thread t =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    URL url = new URL(u);
                    System.out.println("Link : " + u);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();

                    // System.out.println("Response Code : " + con.getInputStream().available());
                    con.setRequestProperty("Accept-Encoding", "gzip,deflate");
                    con.setRequestProperty(
                        "User-Agent",
                        "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36");

                    Map<String, List<String>> map = con.getHeaderFields();

                    for (String object : map.keySet()) {
                      System.out.println(object + " --> " + map.get(object));
                    }

                    System.out.println("Response Code : " + con.getResponseCode());
                    System.out.println("length :" + con.getContentLength());
                    System.out.println("Message " + con.getResponseMessage());

                    InputStream inputStream = con.getInputStream();
                    String path = System.getenv("OPENSHIFT_JBOSSAS_DIR");
                    FileOutputStream fileOutputStream = new FileOutputStream(path + "test.zip");
                    byte[] buffer = new byte[1024];
                    System.out.println(inputStream.available());
                    int bytesRead = 10;
                    while (true) {
                      //   System.out.print("--");
                      bytesRead = inputStream.read(buffer);
                      //   System.out.println(bytesRead);
                      if (bytesRead == -1) {
                        break;
                      }
                      fileOutputStream.write(buffer, 0, bytesRead);
                      // System.out.print(">");
                    }
                    fileOutputStream.close();

                    System.out.println("File Completed");
                  } catch (IOException ex) {
                    Logger.getLogger(MakeData.class.getName()).log(Level.SEVERE, null, ex);
                  }
                }
              });
      t.start();

      //            System.out.println(allLinks.get(0));
      //            System.out.println(webClient.getCookieManager().getCookies(new
      // URL(allLinks.get(0))).size());
      //            // System.out.println(httpPage.asText());
      //             HtmlPage httpPage = webClient.getPage(allLinks.get(0));
      //
      //           // final String pageAsXml = page1.asXml();
      //            // InputStream inputStream=httpPage.getWebResponse().getContentAsStream();
      //           //  inputStream.available();
      //              System.out.println("Code : "+httpPage.getWebResponse().getStatusMessage());
      //               System.out.println("Code : "+httpPage.getWebResponse().getContentType());
      //                System.out.println("netCode :
      // "+httpPage.getWebResponse().getContentCharset());
      //
      // out.println("<br/><br/>Code : "+httpPage.getWebResponse().getStatusCode());
      // out.println("<br/><br/>Code : "+httpPage.getWebResponse().getContentType());
      // out.println("<br/><br/>Code : "+httpPage.getWebResponse().getContentCharset());

      // final String pageAsText = page1.asText();

      // out.println(pageAsXml);
      webClient.closeAllWindows();
      out.println("<h1>Servlet NewServlet at " + request.getContextPath() + "</h1>");
      out.println("</body>");
      out.println("</html>");
    } finally {
      out.close();
    }
  }
Beispiel #17
0
  public static void main(String[] args) {
    try {
      System.out.println("Starting application...");
      java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);

      wc = new WebClient(BrowserVersion.FIREFOX_10);
      // wc = new WebClient(BrowserVersion.FIREFOX_10, "50.117.67.126", 3131);
      final DefaultCredentialsProvider scp = new DefaultCredentialsProvider();
      scp.addCredentials("754d539bc6ade1ad", "454585f105747a76");
      // wc.setCredentialsProvider(scp);
      wc.setJavaScriptEnabled(false);
      wc.setThrowExceptionOnScriptError(false);
      wc.setThrowExceptionOnFailingStatusCode(false);

      // Get the first page
      HtmlPage page = wc.getPage("http://torn.com/index.php");
      if (page.asText().contains("You are no longer logged in."))
        page = login(page, "tempaccount", "temp123");
      else System.out.println("Already logged in.");

      System.out.println("Index.php loaded.");
      int loop = 0;
      int errors = 0;
      while (true) {

        System.out.println("Beginning loop " + loop + "...");
        loop++;
        try {
          if (inHospital(page) || inJail(page)) {
            System.out.println("Sleeping 5 minutes...");
            Thread.sleep(1000 * 5 * 60);
          } else {
            System.out.println("Loading page...");
            wc.setJavaScriptEnabled(true);
            page = wc.getPage("http://torn.com/gym.php");
            // page = wc.getPage("http://torn.com/crimes.php");
            while (onCaptcha(page)) {
              wc.setJavaScriptEnabled(true);
              System.out.println("Captcha encountered.");
              page = solveCaptcha(page);
              wc.setJavaScriptEnabled(false);
            }
            // System.out.println(page.getWebResponse().getContentAsString());
            trainStrength(page, 20);
            // doCrime(page, 5);
            System.out.println("Sleeping 30 minutes...");
            Thread.sleep(1000 * 15);
          }
          page = loadIndex();
        } catch (Exception e) {
          System.out.println(e.toString());
          errors++;
          page = loadIndex();
          if (errors > 3) System.exit(1);
        }
      }

    } catch (Exception e) {
      wc.closeAllWindows();
      e.printStackTrace();
    }
  }
 @Override
 public void release() {
   webClient.closeAllWindows();
   webClient = null;
   super.release();
 }
Beispiel #19
0
  public void initCookie() {

    // try {
    // System.setProperty("webdriver.chrome.driver", "./chromedriver.exe");
    // driver = new ChromeDriver();
    // driver.get("http://weibo.com/");
    // WebElement e = driver.findElement(By.name("username"));
    // e.sendKeys(account.getUsername());
    // e = driver.findElement(By.name("password"));
    // e.sendKeys(account.getPassword());
    // e = driver.findElement(By
    // .xpath("//span[@node-type='submitStates']"));
    // e.click();
    // Set<Cookie> cookies = driver.manage().getCookies();
    // // httpClient.startSession(new URL("http://weibo.com"));
    // HttpState state = new HttpState();
    // String ck = "";
    // for (Cookie c : cookies) {
    // ck += c.getName() + "=" + c.getValue() + "; ";
    // }
    // account.setCookie(ck);
    // driver.close();
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    try {
      HttpClient httpClient = new HttpClient();
      httpClient.setTimeout(30000);
      HostConfiguration conf = new HostConfiguration();
      conf.setHost(new URI("http://www.weibo.com"));
      httpClient.setHostConfiguration(conf);
      httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
      httpClient.getParams().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true);
      httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
      GetMethod method =
          new GetMethod(
              "http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=&rsakt=mod&client=ssologin.js(v1.4.11)&_=1387711657507");
      httpClient.executeMethod(method);
      String s = method.getResponseBodyAsString();
      int idx;
      idx = s.indexOf("servertime\":") + "servertime\":".length();
      String servertime = s.substring(idx, s.indexOf(",", idx));
      idx = s.indexOf("nonce\":\"") + "nonce\":\"".length();
      String nonce = s.substring(idx, s.indexOf("\"", idx));
      idx = s.indexOf("pubkey\":\"") + "pubkey\":\"".length();
      String pubkey = s.substring(idx, s.indexOf("\"", idx));
      idx = s.indexOf("rsakv\":\"") + "rsakv\":\"".length();
      String rsakv = s.substring(idx, s.indexOf("\"", idx));
      PostMethod post =
          new PostMethod("http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.11)");

      final WebClient webClient = new WebClient();
      HtmlPage page = webClient.getPage("http://www.baidu.com/");
      InputStream is = Testweibo.class.getClassLoader().getResourceAsStream("weibo.js");
      String script = IOUtils.toString(is);
      is.close();
      ScriptResult sr = page.executeJavaScript(script);
      script =
          "sinaSSOController.rsaPubkey = '"
              + pubkey
              + "';sinaSSOController.servertime = '"
              + servertime
              + "';sinaSSOController.nonce = '"
              + nonce
              + "';sinaSSOController.rsakv = '"
              + rsakv
              + "';sinaSSOController.from = 'weibo';sinaSSOController.useTicket = 1;";
      sr = page.executeJavaScript(script);
      script =
          "sinaSSOController.login('"
              + account.getUsername()
              + "','"
              + account.getPassword()
              + "',7);";
      sr = page.executeJavaScript(script);
      NativeObject no = (NativeObject) sr.getJavaScriptResult();

      for (Object o : no.getAllIds()) {
        // System.out.println(o + "=>" + no.get(o));
        post.setParameter(o + "", no.get(o) + "");
      }
      webClient.closeAllWindows();
      post.setParameter("gateway", "1");
      post.setParameter("savestate", "7");
      post.setParameter("useticket", "1");
      post.setParameter(
          "pagerefer",
          "http://login.sina.com.cn/sso/logout.php?entry=miniblog&r=http%3A%2F%2Fweibo.com%2Flogout.php%3Fbackurl%3D%252F");
      post.setParameter("vsnf", "1");
      post.setParameter("encoding", "UTF-8");
      post.setParameter("prelt", "140");
      post.setParameter(
          "url",
          "http://www.weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack");
      post.setParameter("returntype", "META");
      httpClient.executeMethod(post);
      s = new String(post.getResponseBody(), "UTF-8");
      idx = s.indexOf("location.replace('") + "location.replace('".length();
      String url = s.substring(idx, s.indexOf("'", idx));
      //			System.out.println(url);
      logger.debug(url);
      method = new GetMethod(url);
      httpClient.executeMethod(method);
      ;
      //			System.out.println(method.getResponseBodyAsString());
      logger.debug(method.getResponseBodyAsString());
      //			 method = new GetMethod("http://weibo.com/");
      //			 httpClient.executeMethod(method);
      //			 System.out.println(method.getURI());
      //			 System.out.println(new String(method.getResponseBody(),"UTF-8"));

      //			String ck = "";
      //			for (Cookie c : httpClient.getState().getCookies()) {
      ////				if(c.getDomain().equals(".weibo.com")||c.getDomain().equals("weibo.com"))
      //				ck += c.getName() + "=" + c.getValue() + "; ";
      //			}
      //			account.setCookie(ck);
      clientMap.put(account.getUsername(), httpClient);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }