public List<StepLog> getStepLog(Long stepCount, String feedURL) throws IOException {
    // Get steps details
    HttpGet httpGet = new HttpGet(feedURL + "?pageSize=" + stepCount); // hack !!!

    // Handle CSRF tokens cookies
    client.setCookieStore(handleCsrfCookies(client.getCookieStore()));

    // Authenticate
    if (OOBuildStep.getEncodedCredentials() != null) {
      httpGet.addHeader(
          "Authorization", "Basic " + new String(OOBuildStep.getEncodedCredentials()));
    }

    // Execute the request
    HttpResponse response = client.execute(httpGet);

    // Verify the response is OK
    Assert.isTrue(
        response.getStatusLine().getStatusCode() == 200,
        "Invalid response code [" + response.getStatusLine().getStatusCode() + "]");

    String responseBody = EntityUtils.toString(response.getEntity());

    List<StepLog> stepLog =
        gson.fromJson(responseBody, new TypeToken<List<StepLog>>() {}.getType());
    //        List<StepLog> stackTrace = createStackTrace(stepLog, "0");
    //        listener.annotate(new SimpleHtmlNote(stackTraceAsString(stackTrace)));

    //        setJSONExecutionResult(responseBody);
    //        responseBody = formatResult(responseBody);

    return stepLog;
    //        return "";
  }
  public static String getUrl(String url, int maxRetries) throws IOException {
    String result = null;
    int retries = 0;
    DefaultHttpClient httpclient = new DefaultHttpClient(defaultHttpParams);
    httpclient.setCookieStore(null);
    HttpGet httpget = new HttpGet(url);
    while (retries <= maxRetries && result == null) {
      try {
        retries++;
        HttpEntity entity = httpclient.execute(httpget).getEntity();

        if (entity != null) {
          result = EntityUtils.toString(entity).trim();
        }
      } catch (SocketException se) {
        if (retries > maxRetries) {
          throw se;
        } else {
          Log.v(TAG, "SocketException, retrying " + retries);
        }
      }
    }

    return result;
  }
Example #3
0
 public static HttpClient getNewHttpClient() {
   try {
     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
     trustStore.load(null, null);
     SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
     sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     HttpParams params = new BasicHttpParams();
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
     HttpProtocolParams.setUserAgent(
         params,
         "Mozilla/5.0 (Windows; Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36");
     SchemeRegistry registry = new SchemeRegistry();
     registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
     registry.register(new Scheme("https", sf, 443));
     ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
     @SuppressWarnings("resource")
     DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
     httpClient.setCookieStore(new BasicCookieStore());
     httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
     httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
     return new DefaultHttpClient(ccm, params);
   } catch (Exception e) {
     return new DefaultHttpClient();
   }
 }
    public static synchronized DefaultHttpClient getThreadSafeClient() {

      if (clientThreadSafe != null) return clientThreadSafe;

      clientThreadSafe = new DefaultHttpClient();

      ClientConnectionManager mgr = clientThreadSafe.getConnectionManager();

      HttpParams params = clientThreadSafe.getParams();

      // timeout
      // int timeoutConnection = 25000;
      int timeoutConnection = 10000;
      HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);
      // int timeoutSocket = 25000;
      int timeoutSocket = 10000;
      HttpConnectionParams.setSoTimeout(params, timeoutSocket);
      clientThreadSafe =
          new DefaultHttpClient(
              new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);

      // disable requery
      clientThreadSafe.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
      // persistent cookies
      clientThreadSafe.setCookieStore(SmartLibMU.getCookieStore());

      return clientThreadSafe;
    }
Example #5
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);
  }
  /**
   * Adds a set of cookies to the HTTPClient. Pass in a HashMap of <String, Object> to add the
   * cookie values to the client. These cookies persist until removed.
   *
   * @param cookies a HashMap of cookies
   * @param url the domain URL of the cookie
   */
  public void setCookies(HashMap<String, String> cookies, String url) {
    if (cookies == null) {
      return;
    }

    // Set cookies
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    // Create cookie store
    BasicCookieStore store =
        (BasicCookieStore)
            (client.getCookieStore() == null ? new BasicCookieStore() : client.getCookieStore());

    // Add cookies to request
    for (Map.Entry<String, String> entry : cookies.entrySet()) {
      BasicClientCookie cookie = new BasicClientCookie(entry.getKey(), entry.getValue());
      if (url != null) {
        cookie.setDomain(url);
      }
      cookie.setPath("/");
      store.addCookie(cookie);
    }

    // Add the cookie
    client.setCookieStore(store);
  }
  public DefaultHttpClient getClientNoProxy() {

    httpclient = new DefaultHttpClient(cm);
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
    httpclient.setCookieStore(new TwitterLoginCookieStore());
    return httpclient;
  }
 public DefaultHttpClient getClientByIpAndPort(String ip, int port) {
   httpclient = new DefaultHttpClient(cm);
   HttpHost proxy = new HttpHost(ip, port);
   httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
   httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
   httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
   httpclient.setCookieStore(new TwitterLoginCookieStore());
   return httpclient;
 }
 public DefaultHttpClient getClient() {
   httpclient = new DefaultHttpClient(cm);
   HttpHost proxy = new HttpHost("127.0.0.1", 8580);
   httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
   httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
   httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
   httpclient.setCookieStore(new TwitterLoginCookieStore());
   return httpclient;
 }
Example #10
0
 public void loadCookies(File file) {
   try {
     FileInputStream fis = new FileInputStream(file);
     ObjectInputStream ois = new ObjectInputStream(fis);
     httpClient.setCookieStore((CookieStore) ois.readObject());
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #11
0
  /** Create clone of existing RLHttpClient object */
  @Override
  public RLHttpClient clone() {
    RLHttpClient brother = new RLHttpClient(mConnectionTimeout, mSocketTimeout);

    if (mHttpClient != null) {
      CookieStore cookieStore = mHttpClient.getCookieStore();
      DefaultHttpClient cloneHttpClient = (DefaultHttpClient) brother.getHttpClient();
      cloneHttpClient.setCookieStore(cookieStore);
    }

    return brother;
  }
Example #12
0
  public NoahHi(String username, String password) throws IOException {
    this.username = username;
    this.password = password;
    HttpClientFactory httpClientFactory = new HttpClientFactory();
    httpClient = httpClientFactory.generateClient(username, password);

    login();
    welcome();
    init();
    messageHttpClient = new DefaultHttpClient();
    messageHttpClient.setCookieStore(httpClient.getCookieStore());
    //        pick();
  }
  public DefaultHttpClient getClientNoProxy() {

    httpclient = new DefaultHttpClient(cm);
    // 通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
    httpclient
        .getConnectionManager()
        .getSchemeRegistry()
        .register(new Scheme("https", socketFactory, 443));
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
    // httpclient.setHttpRequestRetryHandler(new myRetryHandler());
    httpclient.setCookieStore(new GoogleLoginCookieStore());
    return httpclient;
  }
 public DefaultHttpClient getClientByIpAndPort(String ip, int port) {
   httpclient = new DefaultHttpClient(cm);
   // 通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
   httpclient
       .getConnectionManager()
       .getSchemeRegistry()
       .register(new Scheme("https", socketFactory, 443));
   HttpHost proxy = new HttpHost(ip, port);
   httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
   httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
   httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
   httpclient.setCookieStore(new GoogleLoginCookieStore());
   return httpclient;
 }
  private String fetchData(String url) {
    StringBuilder data = new StringBuilder();
    boolean isSuccess = false;
    HttpClient stageClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    RailyatriCookies railyatriCookies = getRailyatriCookies();
    if (railyatriCookies != null) {
      ((DefaultHttpClient) stageClient).setCookieSpecs(railyatriCookies.getCookieSpecRegistry());
      ((DefaultHttpClient) stageClient).setCookieStore(railyatriCookies.getCookieStore());
    }

    httpGet.setHeader("Accept", "application/json");
    httpGet.setHeader(
        "User-Agent",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22");
    httpGet.setHeader("Accept-Encoding", "gzip,deflate,sdch");
    try {
      HttpResponse response = stageClient.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
          data.append(line);
          isSuccess = true;
        }

      } else {
        Log.e(tag, "Failed to access: " + url + ". status code = " + statusCode);
        isSuccess = false;
      }
    } catch (ClientProtocolException clientProtocolException) {
      clientProtocolException.printStackTrace();
      Log.e(tag, clientProtocolException.getMessage());
      isSuccess = false;
    } catch (IOException ioException) {
      ioException.printStackTrace();
      Log.e(tag, ioException.getMessage());
      isSuccess = false;
    }

    if (isSuccess) {
      return data.toString();
    } else {
      return null;
    }
  }
  public static String getUrlByPost(
      String url, Map<String, String> params, Map<String, String> headers, int maxRetries)
      throws IOException {
    String result = null;
    int retries = 0;
    DefaultHttpClient httpclient = new DefaultHttpClient(defaultHttpParams);
    httpclient.setCookieStore(null);

    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    if (params != null) {
      Set<Entry<String, String>> paramsSet = params.entrySet();
      for (Entry<String, String> entry : paramsSet) {
        formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
      }
    }

    UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formParams, UTF8);
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(postEntity);

    if (headers != null) {
      Set<Entry<String, String>> headersSet = headers.entrySet();
      for (Entry<String, String> entry : headersSet) {
        httppost.setHeader(entry.getKey(), entry.getValue());
      }
    }

    while (retries < maxRetries && result == null) {
      try {
        retries++;
        HttpEntity responseEntity = httpclient.execute(httppost).getEntity();
        if (responseEntity != null) {
          result = EntityUtils.toString(responseEntity).trim();
        }
      } catch (SocketException se) {
        if (retries > maxRetries) {
          throw se;
        } else {
          Log.v(TAG, "SocketException, retrying " + retries, se);
        }
      }
    }

    return result;
  }
Example #17
0
 private void initClient() {
   // TODO Auto-generated method stub
   client = new DefaultHttpClient();
   int TIMEOUT = 30 * 1000;
   HttpParams params = client.getParams();
   HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
   HttpConnectionParams.setSoTimeout(params, TIMEOUT);
   params.setParameter(
       "User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0");
   params.setParameter(
       "http.useragent", "Mozilla/5.0 (X11; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0");
   params.setParameter("Accept-Language", "zh-CN,zh;q=0.8");
   params.setParameter("Accept-Encoding", "gzip,deflate,sdch");
   params.setParameter(
       "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
   client.setParams(params);
   BasicCookieStore localBasicCookieStore = new BasicCookieStore();
   client.setCookieStore(localBasicCookieStore);
 }
Example #18
0
  public RestResponse execute(HttpRequestBase request, RestResponse restResponse) {
    if (restResponse == null) restResponse = new RestResponse();

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, Timeout);
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreProtocolPNames.USER_AGENT, UserAgent);
    DefaultHttpClient client = new DefaultHttpClient(params);
    client.setCookieStore(cookieJar);

    try {
      logCallDetails(request);
      HttpResponse response = client.execute(request);
      restResponse.setResponse(response);
    } catch (ClientProtocolException e) {
      restResponse.setException(e);
    } catch (IOException e) {
      restResponse.setException(e);
    }

    return restResponse;
  }
  @Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "hostnameVerifier"})
  @Test
  public void sessionWorkFlow1(
      final String redirectUris,
      final String userId,
      final String userSecret,
      final String redirectUri,
      String hostnameVerifier)
      throws Exception {
    showTitle("sessionWorkFlow1");

    // Register client
    RegisterRequest registerRequest =
        new RegisterRequest(
            ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(
        registerResponse.getStatus(),
        200,
        "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();

    DefaultHttpClient httpClient =
        createHttpClient(HostnameVerifierType.fromString(hostnameVerifier));
    CookieStore cookieStore = new BasicCookieStore();
    httpClient.setCookieStore(cookieStore);
    ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);

    AuthorizationRequest authorizationRequest1 =
        new AuthorizationRequest(
            Arrays.asList(ResponseType.CODE),
            clientId,
            Arrays.asList("openid", "profile", "email"),
            redirectUri,
            null);

    authorizationRequest1.setAuthUsername(userId);
    authorizationRequest1.setAuthPassword(userSecret);
    authorizationRequest1.getPrompts().add(Prompt.NONE);
    authorizationRequest1.setState("af0ifjsldkj");
    authorizationRequest1.setRequestSessionState(true);

    AuthorizeClient authorizeClient1 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient1.setRequest(authorizationRequest1);
    AuthorizationResponse authorizationResponse1 = authorizeClient1.exec(clientExecutor);

    showClient(authorizeClient1);
    assertEquals(
        authorizationResponse1.getStatus(),
        302,
        "Unexpected response code: " + authorizationResponse1.getStatus());
    assertNotNull(authorizationResponse1.getLocation(), "The location is null");
    assertNotNull(authorizationResponse1.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse1.getSessionState(), "The session state is null");
    assertNotNull(authorizationResponse1.getState(), "The state is null");
    assertNotNull(authorizationResponse1.getScope(), "The scope is null");

    String code1 = authorizationResponse1.getCode();
    String sessionState = authorizationResponse1.getSessionState();

    // TV sends the code to the Backend
    // We don't use httpClient and cookieStore during this call

    ////////////////////////////////////////////////
    //             Backend  1 side. Code 1        //
    ////////////////////////////////////////////////

    // Get the access token
    TokenClient tokenClient1 = new TokenClient(tokenEndpoint);
    TokenResponse tokenResponse1 =
        tokenClient1.execAuthorizationCode(code1, redirectUri, clientId, clientSecret);

    showClient(tokenClient1);
    assertEquals(
        tokenResponse1.getStatus(), 200, "Unexpected response code: " + tokenResponse1.getStatus());
    assertNotNull(tokenResponse1.getEntity(), "The entity is null");
    assertNotNull(tokenResponse1.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse1.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse1.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse1.getRefreshToken(), "The refresh token is null");

    String accessToken1 = tokenResponse1.getAccessToken();

    // Get the user's claims
    UserInfoClient userInfoClient1 = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse userInfoResponse1 = userInfoClient1.execUserInfo(accessToken1);

    showClient(userInfoClient1);
    assertEquals(
        userInfoResponse1.getStatus(),
        200,
        "Unexpected response code: " + userInfoResponse1.getStatus());
    assertNotNull(
        userInfoResponse1.getClaim(JwtClaimName.SUBJECT_IDENTIFIER),
        "Unexpected result: subject not found");
    assertNotNull(
        userInfoResponse1.getClaim(JwtClaimName.NAME), "Unexpected result: name not found");
    assertNotNull(
        userInfoResponse1.getClaim(JwtClaimName.GIVEN_NAME),
        "Unexpected result: given_name not found");
    assertNotNull(
        userInfoResponse1.getClaim(JwtClaimName.FAMILY_NAME),
        "Unexpected result: family_name not found");
    assertNotNull(
        userInfoResponse1.getClaim(JwtClaimName.EMAIL), "Unexpected result: email not found");

    ////////////////////////////////////////////////
    //             TV side. Code 2                //
    ////////////////////////////////////////////////

    AuthorizationRequest authorizationRequest2 =
        new AuthorizationRequest(
            Arrays.asList(ResponseType.CODE),
            clientId,
            Arrays.asList("openid", "profile", "email"),
            redirectUri,
            null);

    authorizationRequest2.getPrompts().add(Prompt.NONE);
    authorizationRequest2.setState("af0ifjsldkj");
    authorizationRequest2.setSessionState(sessionState);

    AuthorizeClient authorizeClient2 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient2.setRequest(authorizationRequest2);
    AuthorizationResponse authorizationResponse2 = authorizeClient2.exec(clientExecutor);

    showClient(authorizeClient2);
    assertEquals(
        authorizationResponse2.getStatus(),
        302,
        "Unexpected response code: " + authorizationResponse2.getStatus());
    assertNotNull(authorizationResponse2.getLocation(), "The location is null");
    assertNotNull(authorizationResponse2.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse2.getState(), "The state is null");
    assertNotNull(authorizationResponse2.getScope(), "The scope is null");

    String code2 = authorizationResponse2.getCode();

    // TV sends the code to the Backend
    // We don't use httpClient and cookieStore during this call

    ////////////////////////////////////////////////
    //             Backend  2 side. Code 2        //
    ////////////////////////////////////////////////

    // Get the access token
    TokenClient tokenClient2 = new TokenClient(tokenEndpoint);
    TokenResponse tokenResponse2 =
        tokenClient2.execAuthorizationCode(code2, redirectUri, clientId, clientSecret);

    showClient(tokenClient2);
    assertEquals(
        tokenResponse2.getStatus(), 200, "Unexpected response code: " + tokenResponse2.getStatus());
    assertNotNull(tokenResponse2.getEntity(), "The entity is null");
    assertNotNull(tokenResponse2.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse2.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse2.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse2.getRefreshToken(), "The refresh token is null");

    String accessToken2 = tokenResponse2.getAccessToken();

    // Get the user's claims
    UserInfoClient userInfoClient2 = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse userInfoResponse2 = userInfoClient2.execUserInfo(accessToken2);

    showClient(userInfoClient2);
    assertEquals(
        userInfoResponse2.getStatus(),
        200,
        "Unexpected response code: " + userInfoResponse2.getStatus());
    assertNotNull(
        userInfoResponse2.getClaim(JwtClaimName.SUBJECT_IDENTIFIER),
        "Unexpected result: subject not found");
    assertNotNull(
        userInfoResponse2.getClaim(JwtClaimName.NAME), "Unexpected result: name not found");
    assertNotNull(
        userInfoResponse2.getClaim(JwtClaimName.GIVEN_NAME),
        "Unexpected result: given_name not found");
    assertNotNull(
        userInfoResponse2.getClaim(JwtClaimName.FAMILY_NAME),
        "Unexpected result: family_name not found");
    assertNotNull(
        userInfoResponse2.getClaim(JwtClaimName.EMAIL), "Unexpected result: email not found");
  }
  /**
   * 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;
  }
  public WaitExecutionResult waitExecutionComplete(
      TriggeredExecutionDetailsVO triggeredExecutionDetailsVO,
      String timeout,
      BuildListener listener,
      String urlString)
      throws InterruptedException, IOException {
    feedURL = triggeredExecutionDetailsVO.getFeedUrl();

    // close connection
    //        is.close();

    // Read run details
    long defaultTimeout = 600000;
    Long timeoutLong = timeout.isEmpty() ? defaultTimeout : Long.parseLong(timeout);
    listener.getLogger().println("Flow execution timeout : " + timeoutLong + " ms");

    // Wait the run will completed
    List<ExecutionSummaryVO> executionSummary;
    ExecutionStatusState executionStatusState;
    int prevStepCount = 0;
    Boolean newLine = false;
    do {
      Long sleepIntervalInMs = timeoutLong > 5000 ? 5000 : timeoutLong;
      timeoutLong -= (sleepIntervalInMs);
      Thread.sleep(sleepIntervalInMs);

      // Get run details
      HttpGet httpGet = new HttpGet(urlString + EXECUTIONS_API + runId + EXECUTE_SUMMARY_POSTFIX);

      // Handle CSRF tokens cookies
      client.setCookieStore(handleCsrfCookies(client.getCookieStore()));

      // Authenticate
      if (OOBuildStep.getEncodedCredentials() != null) {
        httpGet.addHeader(
            "Authorization", "Basic " + new String(OOBuildStep.getEncodedCredentials()));
      }

      // Execute the request
      HttpResponse response = client.execute(httpGet);

      // Verify the response is OK
      Assert.isTrue(
          response.getStatusLine().getStatusCode() == 200,
          "Invalid response code [" + response.getStatusLine().getStatusCode() + "]");

      String responseBody = EntityUtils.toString(response.getEntity());

      executionSummary =
          gson.fromJson(responseBody, new TypeToken<List<ExecutionSummaryVO>>() {}.getType());
      executionStatusState = executionSummary.get(0).getStatus();

      // get steps details for steps progress
      httpGet = new HttpGet(urlString + EXECUTIONS_API + runId + EXECUTION_STEPS_COUNT_POSTFIX);

      // Handle CSRF tokens cookies
      client.setCookieStore(handleCsrfCookies(client.getCookieStore()));

      // Authenticate
      if (OOBuildStep.getEncodedCredentials() != null) {
        httpGet.addHeader(
            "Authorization", "Basic " + new String(OOBuildStep.getEncodedCredentials()));
      }

      // Execute the request
      response = client.execute(httpGet);

      // Verify the response is OK
      Assert.isTrue(
          response.getStatusLine().getStatusCode() == 200,
          "Invalid response code [" + response.getStatusLine().getStatusCode() + "]");

      responseBody = EntityUtils.toString(response.getEntity());

      // printing steps progress
      int currentStepCount = gson.fromJson(responseBody, new TypeToken<Integer>() {}.getType());

      if (currentStepCount > prevStepCount) {
        if (newLine) {
          listener.getLogger().println();
        }
        listener.getLogger().println(currentStepCount + " steps were completed");
        newLine = false;
      } else {
        listener.getLogger().print(".");
        newLine = true;
      }

      prevStepCount = currentStepCount;

    } while (timeoutLong > 0
        && (executionStatusState.equals(ExecutionStatusState.RUNNING)
            || executionStatusState.equals(ExecutionStatusState.PENDING_PAUSE)));

    // get full status name
    String runResult;
    if (executionStatusState.equals(ExecutionStatusState.COMPLETED)) {
      runResult = executionStatusState + " - " + executionSummary.get(0).getResultStatusType();
    } else {
      // TODO handle also paused runs
      runResult = executionStatusState.name();
    }

    WaitExecutionResult waitExecutionResult = new WaitExecutionResult();
    waitExecutionResult.setLastExecutionResult(executionSummary.get(0).getResultStatusType());
    waitExecutionResult.setLastExecutionStatus(executionStatusState);
    waitExecutionResult.setTimedOut(
        timeoutLong <= 0
            && (executionStatusState.equals(ExecutionStatusState.RUNNING)
                || executionStatusState.equals(ExecutionStatusState.PENDING_PAUSE)));
    waitExecutionResult.setStepCount(prevStepCount);

    return waitExecutionResult;
  }
  @Parameters({"redirectUris", "redirectUri", "userInum", "userEmail", "hostnameVerifier"})
  @Test
  public void sessionWorkFlow2(
      final String redirectUris,
      final String redirectUri,
      final String userInum,
      final String userEmail,
      final String hostnameVerifier)
      throws Exception {
    showTitle("sessionWorkFlow2");

    // Register client
    RegisterRequest registerRequest =
        new RegisterRequest(
            ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(
        registerResponse.getStatus(),
        200,
        "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();

    DefaultHttpClient httpClient =
        createHttpClient(HostnameVerifierType.fromString(hostnameVerifier));
    CookieStore cookieStore = new BasicCookieStore();
    httpClient.setCookieStore(cookieStore);
    ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);

    // Authorization code flow to authenticate on B1

    AuthorizationRequest authorizationRequest1 =
        new AuthorizationRequest(
            Arrays.asList(ResponseType.CODE),
            clientId,
            Arrays.asList("openid", "profile", "email"),
            redirectUri,
            null);

    authorizationRequest1.addCustomParameter("mail", userEmail);
    authorizationRequest1.addCustomParameter("inum", userInum);
    authorizationRequest1.getPrompts().add(Prompt.NONE);
    authorizationRequest1.setState("af0ifjsldkj");
    authorizationRequest1.setAuthorizationMethod(AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER);
    authorizationRequest1.setRequestSessionState(true);

    AuthorizeClient authorizeClient1 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient1.setRequest(authorizationRequest1);
    AuthorizationResponse authorizationResponse1 = authorizeClient1.exec(clientExecutor);

    showClient(authorizeClient1);
    assertEquals(
        authorizationResponse1.getStatus(),
        302,
        "Unexpected response code: " + authorizationResponse1.getStatus());
    assertNotNull(authorizationResponse1.getLocation(), "The location is null");
    assertNotNull(authorizationResponse1.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse1.getSessionState(), "The session id is null");
    assertNotNull(authorizationResponse1.getState(), "The state is null");
    assertNotNull(authorizationResponse1.getScope(), "The scope is null");

    String authorizationCode1 = authorizationResponse1.getCode();
    String sessionState = authorizationResponse1.getSessionState();

    TokenRequest tokenRequest1 = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest1.setCode(authorizationCode1);
    tokenRequest1.setRedirectUri(redirectUri);
    tokenRequest1.setAuthUsername(clientId);
    tokenRequest1.setAuthPassword(clientSecret);
    tokenRequest1.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    TokenClient tokenClient1 = new TokenClient(tokenEndpoint);
    tokenClient1.setRequest(tokenRequest1);
    TokenResponse tokenResponse1 = tokenClient1.exec();

    showClient(tokenClient1);
    assertEquals(
        tokenResponse1.getStatus(), 200, "Unexpected response code: " + tokenResponse1.getStatus());
    assertNotNull(tokenResponse1.getEntity(), "The entity is null");
    assertNotNull(tokenResponse1.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse1.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse1.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse1.getRefreshToken(), "The refresh token is null");

    // User wants to authenticate on B2 (without sending its credentials)

    AuthorizationRequest authorizationRequest2 =
        new AuthorizationRequest(
            Arrays.asList(ResponseType.CODE),
            clientId,
            Arrays.asList("openid", "profile", "email"),
            redirectUri,
            null);

    authorizationRequest2.getPrompts().add(Prompt.NONE);
    authorizationRequest2.setState("af0ifjsldkj");
    authorizationRequest2.setSessionState(sessionState);

    AuthorizeClient authorizeClient2 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient2.setRequest(authorizationRequest2);
    AuthorizationResponse authorizationResponse2 = authorizeClient2.exec(clientExecutor);

    showClient(authorizeClient2);
    assertEquals(
        authorizationResponse2.getStatus(),
        302,
        "Unexpected response code: " + authorizationResponse2.getStatus());
    assertNotNull(authorizationResponse2.getLocation(), "The location is null");
    assertNotNull(authorizationResponse2.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse2.getState(), "The state is null");
    assertNotNull(authorizationResponse2.getScope(), "The scope is null");

    String authorizationCode2 = authorizationResponse2.getCode();

    TokenRequest tokenRequest2 = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest2.setCode(authorizationCode2);
    tokenRequest2.setRedirectUri(redirectUri);
    tokenRequest2.setAuthUsername(clientId);
    tokenRequest2.setAuthPassword(clientSecret);
    tokenRequest2.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    TokenClient tokenClient2 = new TokenClient(tokenEndpoint);
    tokenClient2.setRequest(tokenRequest2);
    TokenResponse tokenResponse2 = tokenClient2.exec();

    showClient(tokenClient2);
    assertEquals(
        tokenResponse2.getStatus(), 200, "Unexpected response code: " + tokenResponse2.getStatus());
    assertNotNull(tokenResponse2.getEntity(), "The entity is null");
    assertNotNull(tokenResponse2.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse2.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse2.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse2.getRefreshToken(), "The refresh token is null");

    // User wants to authenticate on B3 (without sending its credentials)

    AuthorizationRequest authorizationRequest3 =
        new AuthorizationRequest(
            Arrays.asList(ResponseType.CODE),
            clientId,
            Arrays.asList("openid", "profile", "email"),
            redirectUri,
            null);

    authorizationRequest3.getPrompts().add(Prompt.NONE);
    authorizationRequest3.setState("af0ifjsldkj");
    authorizationRequest3.setSessionState(sessionState);

    AuthorizeClient authorizeClient3 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient3.setRequest(authorizationRequest3);
    AuthorizationResponse authorizationResponse3 = authorizeClient2.exec(clientExecutor);

    showClient(authorizeClient3);
    assertEquals(
        authorizationResponse3.getStatus(),
        302,
        "Unexpected response code: " + authorizationResponse3.getStatus());
    assertNotNull(authorizationResponse3.getLocation(), "The location is null");
    assertNotNull(authorizationResponse3.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse3.getState(), "The state is null");
    assertNotNull(authorizationResponse3.getScope(), "The scope is null");

    String authorizationCode3 = authorizationResponse3.getCode();

    TokenRequest tokenRequest3 = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest3.setCode(authorizationCode3);
    tokenRequest3.setRedirectUri(redirectUri);
    tokenRequest3.setAuthUsername(clientId);
    tokenRequest3.setAuthPassword(clientSecret);
    tokenRequest3.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    TokenClient tokenClient3 = new TokenClient(tokenEndpoint);
    tokenClient3.setRequest(tokenRequest3);
    TokenResponse tokenResponse3 = tokenClient3.exec();

    showClient(tokenClient3);
    assertEquals(
        tokenResponse3.getStatus(), 200, "Unexpected response code: " + tokenResponse3.getStatus());
    assertNotNull(tokenResponse3.getEntity(), "The entity is null");
    assertNotNull(tokenResponse3.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse3.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse3.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse3.getRefreshToken(), "The refresh token is null");
  }
  public TriggeredExecutionDetailsVO run10x(
      String selectedFlowUUID,
      List<OOArg> argsToUse,
      String urlString,
      String timeout,
      BuildListener listener,
      String runName)
      throws IOException, InterruptedException {

    final HttpPost httpPost = new HttpPost(urlString + EXECUTIONS_API);

    // Convert inputs to the required type
    Map<String, String> inputs = new HashMap<String, String>();
    for (OOArg arg : argsToUse) {
      inputs.put(arg.getName(), arg.getValue());
    }

    // Create the POST object and add the parameters
    ExecutionVO executionVO = new ExecutionVO();
    executionVO.setUuid(selectedFlowUUID);
    if (runName != null && !runName.equals("")) executionVO.setRunName(runName);
    executionVO.setInputs(inputs);
    String body = gson.toJson(executionVO);
    StringEntity entity = new StringEntity(body, "UTF-8");
    httpPost.setEntity(entity);

    // Authenticate
    if (OOBuildStep.getEncodedCredentials() != null) {
      httpPost.addHeader(
          "Authorization", "Basic " + new String(OOBuildStep.getEncodedCredentials()));
    }

    // Add relevant headers
    httpPost.setHeader(
        "Content-Type", "application/json"); // this is mandatory in order for the request to work

    // Handle CSRF tokens cookies
    client.setCookieStore(handleCsrfCookies(client.getCookieStore()));

    // Execute the request
    HttpResponse response = client.execute(httpPost);

    // Verify the response is 201
    Assert.isTrue(
        response.getStatusLine().getStatusCode() == 201,
        "Invalid response code [" + response.getStatusLine().getStatusCode() + "]");

    // Read the response body
    String responseBody = EntityUtils.toString(response.getEntity());

    //        HttpEntity responseEntity = response.getEntity();
    //        InputStream is = responseEntity.getContent();

    // Extract data from response
    //        JsonObject element = (JsonObject)
    // (parser.parse(OOAccessibilityUtils.convertStreamToString(is)));
    TriggeredExecutionDetailsVO triggeredExecutionDetailsVO =
        gson.fromJson(responseBody, TriggeredExecutionDetailsVO.class);

    runId = triggeredExecutionDetailsVO.getExecutionId();
    listener.getLogger().println("Run ID : " + runId);
    runURL =
        triggeredExecutionDetailsVO.getFeedUrl().split("/oo/")[0]
            + "/oo/#/runtimeWorkspace/runs/"
            + triggeredExecutionDetailsVO.getExecutionId();

    listener.getLogger().println("Execution URL " + runURL);

    return triggeredExecutionDetailsVO;
  }
Example #24
0
  public static File fileDownLoad(
      String uri, String fileDirect, String fileName, final Context context, ProgressDialog pd) {
    File file = null;
    DefaultHttpClient client = new DefaultHttpClient();
    HttpParams httParams = client.getParams();
    HttpConnectionParams.setConnectionTimeout(httParams, 20000);
    HttpConnectionParams.setSoTimeout(httParams, 20000);

    HttpProtocolParams.setContentCharset(httParams, HTTP.UTF_8);
    HttpProtocolParams.setUseExpectContinue(httParams, false);
    if (OrongApplication.cookieStore != null) {
      client.setCookieStore(OrongApplication.cookieStore);
    }
    HttpGet get = new HttpGet(uri);
    try {
      HttpResponse responese = client.execute(get);
      int responeseCode = responese.getStatusLine().getStatusCode();
      if (responeseCode == HttpStatus.SC_OK) {
        HttpEntity httpentity = responese.getEntity();
        int max = (int) httpentity.getContentLength();
        pd.setMax(max);
        if (fileDirect != null) {
          File dire = new File(fileDirect);
          if (!dire.exists()) {
            dire.mkdirs();
          }
          if (dire.exists()) {
            if (fileName == null) {
              fileName = uri.substring(uri.lastIndexOf("/"));
              if (!fileName.endsWith(".apk")) {
                fileName = fileName + ".apk";
              }
            } else {
              fileName = "/" + fileName;
            }
            file = new File(dire + fileName);
            file.createNewFile();
            InputStream is = httpentity.getContent();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len = 0;
            int total = 0;
            while ((len = is.read(buffer)) != -1) {
              fos.write(buffer, 0, len);
              total += len;
              pd.setProgress(total);
            }
            if (total == max) {
              pd.dismiss();
            }
            fos.flush();
            fos.close();
            is.close();
          }
        }
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
    return file;
  }