예제 #1
0
 /**
  * 合并cookie信息放到一个cookie中 此方法会出错,无效。
  *
  * @param client
  */
 private static void mergeCookie(HttpClient client) {
   Cookie[] cookies = client.getState().getCookies();
   if (cookies != null && cookies.length > 0) {
     String cook = cookies[0].getValue();
     for (int i = 1; i < cookies.length; i++) {
       cook += "; " + cookies[i].getName() + "=" + cookies[i].getValue();
     }
     cookies[0].setValue(cook);
     HttpState state = new HttpState();
     state.addCookie(cookies[0]);
     client.setState(state);
   }
 }
예제 #2
0
  private static String[] httpPost(String url, String xml) throws Exception {

    HttpClient client = new HttpClient();

    HttpState state = client.getState();

    Credentials credentials = new UsernamePasswordCredentials("S2VMS", "S2VMS!Q@W#E");
    state.setCredentials(null, null, credentials);
    client.setState(state);
    PostMethod method = new PostMethod(url);

    method.setDoAuthentication(true);

    method.getHostAuthState().setAuthAttempted(true);
    method.getHostAuthState().setAuthRequested(true);
    method.getHostAuthState().setPreemptive();
    method.addRequestHeader("Content-Type", "text/xml");
    method.addRequestHeader("SOAPAction", "http://tempuri.org/GetLinkMedia");

    try {
      method.setRequestBody(xml);

    } catch (Exception e) {
      try {
        ByteArrayRequestEntity entity = new ByteArrayRequestEntity(xml.getBytes());
        method.setRequestEntity(entity);

      } catch (Exception e1) {
        throw new Exception("Impossible to set the xml in the post");
      }
    }

    int iRes = client.executeMethod(method);

    byte[] response = method.getResponseBody();

    String textResponse = new String(response);

    String[] toReturn = {"" + iRes, textResponse};

    return toReturn;
  }
예제 #3
0
  protected void setUp() throws Exception {
    try {
      super.setUp();

      Map initCtx = new HashMap();
      initCtx.put(ProxyBuilder.EXPORTER_TYPE_KEY, HttpInvokerServiceExporter.class);

      HttpClient clientS1C1 =
          new HttpClientWithParams(Collections.singletonMap(ConversationScope.CONV_KEY, "(1)"));
      initCtx.put(ProxyBuilder.HTTP_CLIENT_KEY, clientS1C1);

      beanN1C1 =
          (ITestFacade)
              server1.getProxy(ITestFacade.class, APP_NAME + "/http/" + FASADE_NAME, initCtx);
      beanN2C1 =
          (ITestFacade)
              server2.getProxy(ITestFacade.class, APP_NAME + "/http/" + FASADE_NAME, initCtx);

      HttpClient clientS1C2 =
          new HttpClientWithParams(Collections.singletonMap(ConversationScope.CONV_KEY, "(2)"));
      clientS1C2.setState(
          clientS1C1
              .getState()); // share state across the clients, they should be in the same session
      // now
      initCtx.put(ProxyBuilder.HTTP_CLIENT_KEY, clientS1C2);

      beanN1C2 =
          (ITestFacade)
              server1.getProxy(ITestFacade.class, APP_NAME + "/http/" + FASADE_NAME, initCtx);
      beanN2C2 =
          (ITestFacade)
              server2.getProxy(ITestFacade.class, APP_NAME + "/http/" + FASADE_NAME, initCtx);
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }
  /**
   * The method reads a proxy object from database, makes a GetMethod object, appends required
   * cookies to the HttpClient object. The HttpClient then executes the Getmethod and returns the
   * pagesource to the caller.
   *
   * @param iCount Counter variable for passing thread group information
   * @param url Url to fetch the pagesource for
   * @param followRedirect Boolean variable to specify GetMethod followRedirect value
   * @param doAuthentication Boolean variable to specify GetMethod doAuthentication value
   * @param region the local region of a given url
   * @param objProxyDao the database layer ProxyDao object variable
   * @param useErrsy Boolean variable to specify usage of Errsy as proxy source
   * @return String
   */
  public String getPageSourceWithProxy(
      String url,
      boolean followRedirect,
      boolean doAuthentication,
      String region,
      Boolean useErrsy,
      String google) {

    String page = " ";
    String pageSource = "";
    int i = 0;
    String exception = " ";
    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setSoTimeout(40000);
    clientParams.setConnectionManagerTimeout(40000);
    HttpClient httpclient = new HttpClient(clientParams);
    GetMethod getmethod = null;

    HttpState state = new HttpState();

    //  if (ProxyDao.lstProxyData.size() == 16) {
    ProxyData objProxyData = null;
    // if (!useErrsy) {
    try {
      // objProxyData = ProxyDao.lstProxyData.get(iCount);
      objProxyData = ProxyDao.objProxyData;
      if (objProxyData == null) {
        //                objProxyDao.changeProxy(google);
        objProxyData = ProxyDao.objProxyData;
      }
      httpclient
          .getHostConfiguration()
          .setProxy(objProxyData.getIPAddress(), objProxyData.getPortNo());
    } catch (Exception e) {
      pageSource = i + "@@@@" + exception + "@@@@" + page + "@@@@" + url;
      return pageSource;
    }
    /*} else {
    try {
    objProxyData = new ProxyData(0, "46.227.68.2", 3128, "Mongoose", "I-C5GS0FTAL61L", 0, 0);
    Credentials defaultcreds = new UsernamePasswordCredentials(objProxyData.getProxyUser(), objProxyData.getProxyPassword());
    httpclient.getState().setCredentials(AuthScope.ANY, defaultcreds);
    httpclient.getHostConfiguration().setProxy(objProxyData.getIpaddress(), objProxyData.getPortNo());
    state.setProxyCredentials(null, null, new UsernamePasswordCredentials(objProxyData.getProxyUser(), objProxyData.getProxyPassword()));
    httpclient.setState(state);
    } catch (Exception e) {
    pageSource = i + "@@@@" + exception + "@@@@" + page + "@@@@" + url;
    return pageSource;
    }
    }*/
    try {
      getmethod = new GetMethod(url);
      getmethod.addRequestHeader(
          "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0");
      if (url.contains("bing.com")) {

        if (region.equalsIgnoreCase("co.uk")) {
          getmethod.addRequestHeader(
              "Cookie", "_FP=mkt=en-GB;SRCHHPGUSR=NEWWND=0&NRSLT=50&SRCHLANG=&AS=1;");
        } else if (region.equalsIgnoreCase("com.sg")) {
          getmethod.addRequestHeader(
              "Cookie", "_FP=mkt=en-SG;SRCHHPGUSR=NEWWND=0&NRSLT=50&SRCHLANG=&AS=1;");
        } else if (region.equalsIgnoreCase("com.au")) {
          getmethod.addRequestHeader(
              "Cookie", "_FP=mkt=en-AU;SRCHHPGUSR=NEWWND=0&NRSLT=50&SRCHLANG=&AS=1;");
        } else if (region.equalsIgnoreCase("co.in")) {
          getmethod.addRequestHeader(
              "Cookie", "_FP=mkt=en-IN;SRCHHPGUSR=NEWWND=0&NRSLT=50&SRCHLANG=&AS=1;");
        } else if (region.equalsIgnoreCase("ca")) {
          getmethod.addRequestHeader(
              "Cookie", "_FP=mkt=en-CA;SRCHHPGUSR=NEWWND=0&NRSLT=50&SRCHLANG=&AS=1;");
        } else if (region.equalsIgnoreCase("com.ph")) {
          getmethod.addRequestHeader(
              "Cookie", "_FP=mkt=en-PH;SRCHHPGUSR=NEWWND=0&NRSLT=50&SRCHLANG=&AS=1;");
        } else if (region.equalsIgnoreCase("com.my")) {
          getmethod.addRequestHeader(
              "Cookie", "_FP=mkt=en-WW;SRCHHPGUSR=NEWWND=0&NRSLT=50&SRCHLANG=&AS=1;");
        } else if (region.equalsIgnoreCase("it")) {
          getmethod.addRequestHeader(
              "Cookie", "_FP=mkt=en-IT;SRCHHPGUSR=NEWWND=0&NRSLT=50&SRCHLANG=&AS=1;");
        } else {
          getmethod.addRequestHeader(
              "Cookie", "_FP=mkt=en-US;SRCHHPGUSR=NEWWND=0&NRSLT=50&SRCHLANG=&AS=1;");
        }
      }
      getmethod.setFollowRedirects(true);
      getmethod.setDoAuthentication(true);
      httpclient.getParams().setAuthenticationPreemptive(true);
      httpclient.setState(state);
      String num100Header = "";
      //            if (url.contains("google")) {
      //                int j = 0;
      //                String url1 = "http://www.google.com/";
      //                try {
      //                    GetMethod objGetMethod = new GetMethod(url1);
      //                    j = httpclient.executeMethod(objGetMethod);
      //                    Header responseHeader = objGetMethod.getResponseHeader("Set-Cookie");
      //                    String header = responseHeader.getValue();
      //                    String[] headerValue = header.split(";");
      //
      //                    for (String head : headerValue) {
      //                        if (head.contains("PREF=ID")) {
      //                            header = head;
      //                            break;
      //                        }
      //                    }
      //                    String[] splitAll = header.split(":");
      //                    long time = System.currentTimeMillis()+400;
      //                    String sTime = "" + time;
      //                    sTime = sTime.substring(0, 10);
      //                    //num100Header = splitAll[0].replace("PREF=", "") + ":" + splitAll[1]  +
      // ":LD=en:NR=100:" + splitAll[2] + ":" + splitAll[3] + ":" + splitAll[4];
      //                    num100Header = splitAll[0].replace("PREF=", "") + ":" + splitAll[1] +
      // ":LD=en:NR=100:" + "TM=" + sTime + ":LM=" + sTime + ":SG=2:" + splitAll[4];
      //                    Cookie ck = new Cookie("PREF", "PREF", num100Header);
      //                    httpclient.getState().clearCookies();
      //                    httpclient.getState().addCookie(ck);
      //                    getmethod.addRequestHeader("Host", "www.google.com");
      //                    getmethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1;
      // rv:19.0) Gecko/20100101 Firefox/19.0");
      //                    getmethod.addRequestHeader("Accept",
      // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
      //                    getmethod.addRequestHeader("Accept-Language", "en-US,en;q=0.5");
      //                    getmethod.addRequestHeader("Accept-Encoding", "gzip, deflate");
      //                    getmethod.addRequestHeader("Referer", "https://www.google.com/");
      //                    System.out.println(num100Header);
      //                } catch (Exception ex) {
      //                    exception = ex.getMessage();
      //                    l.debug(ex + "  " + ex.getMessage() + "Exception occured for url" +
      // url);
      //                    pageSource = j + "@@@@" + exception + "@@@@" + page + "@@@@" + url1;
      //                    return pageSource;
      //                }
      //            }
      i = httpclient.executeMethod(getmethod);
      if (i / 100 == 4 || i / 100 == 5) {
        page = "<PROXY ERROR>";

      } else {

        page = getmethod.getResponseBodyAsString();
      }
    } catch (SocketTimeoutException ex) {
      exception = ex.getMessage();
      l.error(ex + "  " + ex.getMessage() + "Exception occured for url" + url);
    } catch (SocketException ex) {
      exception = ex.getMessage();
      l.error(ex + "  " + ex.getMessage() + "Exception occured for url" + url);
    } catch (Exception ex) {
      exception = ex.getMessage();
      l.error(ex + "  " + ex.getMessage() + "Exception occured for url" + url);

    } finally {
      getmethod.releaseConnection();
    }
    pageSource = i + "@@@@" + exception + "@@@@" + page + "@@@@" + url;

    // }
    return pageSource;
  }
  @Test
  public void testMultipleUseOfSession() throws Exception {
    JUnitProperties properties = new JUnitProperties();
    String APP_KEY = properties.getAPIKEY();
    String APP_SECRET = properties.getSECRET();
    String EMAIL = properties.getEMAIL();
    String PASSWORD = properties.getPASS();

    FacebookJaxbRestClient client = new FacebookJaxbRestClient(APP_KEY, APP_SECRET);
    client.setIsDesktop(true);

    HttpClient http = new HttpClient();

    String token = client.auth_createToken();

    HttpClientParams params = new HttpClientParams();
    HttpState initialState = new HttpState();

    http.setParams(params);
    http.setState(initialState);

    GetMethod get =
        new GetMethod(
            "http://www.facebook.com/login.php?api_key=" + APP_KEY + "&v=1.0&auth_token=" + token);
    http.executeMethod(get);

    PostMethod post = new PostMethod("http://www.facebook.com/login.php");
    post.addParameter("api_key", APP_KEY);
    post.addParameter("v", "1.0");
    post.addParameter("auth_token", token);
    post.addParameter("email", EMAIL);
    post.addParameter("pass", PASSWORD);

    http.executeMethod(post);

    String sessionID = client.auth_getSession(token);

    // try 1
    try {
      Long uid = client.users_getLoggedInUser();
      System.out.println("UserID: " + uid);

      client.events_get(uid, null, null, null);
    } catch (Exception e) {
      e.printStackTrace();
    }

    // try 2 with new client constructed with a session ID
    try {
      FacebookJaxbRestClient newClient = new FacebookJaxbRestClient(APP_KEY, APP_SECRET, sessionID);
      newClient.setIsDesktop(true);

      Long uid = newClient.users_getLoggedInUser();
      System.out.println("New CLIENT UserID: " + uid);

      newClient.events_get(uid, null, null, null);
      System.out.println(newClient.getRawResponse());
      System.out.println("NEW CLIENT Events: " + newClient.getRawResponse());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }