Example #1
0
  protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config =
        RequestConfig.custom()
            .setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000)
            .setSocketTimeout(20 * 1000)
            .setMaxRedirects(20)
            .build();

    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    if (apn.hasAuthentication()) {
      credsProvider.setCredentials(
          new AuthScope(
              mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
          new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }

    return HttpClients.custom()
        .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
        .setRedirectStrategy(new LaxRedirectStrategy())
        .setUserAgent("Android-Mms/2.0")
        .setConnectionManager(new BasicHttpClientConnectionManager())
        .setDefaultRequestConfig(config)
        .setDefaultCredentialsProvider(credsProvider)
        .build();
  }
Example #2
0
    public Builder setKerberosAuth(GSSCredentialProvider gssCrendentialProvider) {
      Credentials creds =
          new Credentials() {
            @Override
            public String getPassword() {
              return null;
            }

            @Override
            public Principal getUserPrincipal() {
              return null;
            }
          };
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      credentialsProvider.setCredentials(
          new AuthScope(_host, _port, AuthScope.ANY_REALM, AuthSchemes.SPNEGO), creds);
      _httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

      AuthSchemeProvider authSchemaProvider =
          gssCrendentialProvider == null
              ? new SPNegoSchemeFactory(true)
              : new BasicSPNegoSchemeFactory(true, gssCrendentialProvider);

      _httpClientBuilder.setDefaultAuthSchemeRegistry(
          RegistryBuilder.<AuthSchemeProvider>create()
              .register(AuthSchemes.SPNEGO, authSchemaProvider)
              .build());
      return this;
    }
  public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
        new AuthScope("localhost", 443), new UsernamePasswordCredentials("username", "password"));
    CloseableHttpClient httpclient =
        HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {
      HttpGet httpget = new HttpGet("https://localhost/protected");

      System.out.println("executing request" + httpget.getRequestLine());
      CloseableHttpResponse response = httpclient.execute(httpget);
      try {
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
          System.out.println("Response content length: " + entity.getContentLength());
        }
        EntityUtils.consume(entity);
      } finally {
        response.close();
      }
    } finally {
      httpclient.close();
    }
  }
Example #4
0
 public Builder setUsernameAuth(String username, String password) {
   CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
   credentialsProvider.setCredentials(
       AuthScope.ANY, new UsernamePasswordCredentials(username, password));
   _httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
   return this;
 }
Example #5
0
 /**
  * It is convenient to be able to directly set the Credentials (not the provider) when those
  * credentials are fixed.
  *
  * @param creds
  * @param scope where to use it (i.e. on what host)
  * @throws HTTPException
  */
 public static void setGlobalCredentials(Credentials creds, AuthScope scope) throws HTTPException {
   assert (creds != null);
   if (scope == null) scope = AuthScope.ANY;
   CredentialsProvider provider = new BasicCredentialsProvider();
   provider.setCredentials(scope, creds);
   setGlobalCredentialsProvider(provider, scope);
 }
 /*.................................................................................................................*/
 public HttpClient getHttpClient() {
   // from http://www.artima.com/forums/flat.jsp?forum=121&thread=357685
   CredentialsProvider provider = new BasicCredentialsProvider();
   UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
   provider.setCredentials(AuthScope.ANY, credentials);
   return HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
 }
  public void init() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    ThreadSafeClientConnManager conMan = new ThreadSafeClientConnManager(schemeRegistry);
    conMan.setMaxTotal(maxTotalConnections);
    conMan.setDefaultMaxPerRoute(maxPerRouteConnections);

    httpClient = new DefaultHttpClient(conMan, clientParams);

    if (credentials != null) {
      CredentialsProvider credentialsProvider = httpClient.getCredentialsProvider();
      credentialsProvider.setCredentials(getAuthScope(), credentials);

      // preemptive basic auth hc 4.0 style
      if (authPreemptive) {
        BasicScheme basicAuth = new BasicScheme();
        httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(basicAuth), 0);
      }

      List<String> authpref = new ArrayList<String>();
      authpref.add(AuthPolicy.BASIC);
      // authpref.add(AuthPolicy.DIGEST);
      httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
    }

    if (sslSocketFactory != null) {
      SSLSocketFactory sslSf =
          new SSLSocketFactory(
              sslSocketFactory.getSSLContext(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
      Scheme https = new Scheme("https", 443, sslSf);
      schemeRegistry.register(https);
    }
  }
  public void afterPropertiesSet() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionManager(getPoolingHttpClientConnectionManager());

    if ((_login != null) && (_password != null)) {
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

      credentialsProvider.setCredentials(
          new AuthScope(_hostName, _hostPort), new UsernamePasswordCredentials(_login, _password));

      httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
      httpClientBuilder.setRetryHandler(new HttpRequestRetryHandlerImpl());
    } else {
      if (_logger.isWarnEnabled()) {
        _logger.warn("Login and password are required");
      }
    }

    try {
      setProxyHost(httpClientBuilder);

      _closeableHttpClient = httpClientBuilder.build();

      if (_logger.isDebugEnabled()) {
        _logger.debug("Configured client for " + _protocol + "://" + _hostName);
      }
    } catch (Exception e) {
      _logger.error("Unable to configure client", e);
    }
  }
Example #9
0
 /**
  * It is convenient to be able to directly set the Credentials (not the provider) when those
  * credentials are fixed.
  *
  * @param creds
  * @param scope where to use it (i.e. on what host)
  * @throws HTTPException
  */
 public HTTPSession setCredentials(Credentials creds, AuthScope scope) throws HTTPException {
   assert (creds != null);
   if (scope == null) scope = AuthScope.ANY;
   CredentialsProvider provider = new BasicCredentialsProvider();
   provider.setCredentials(scope, creds);
   setCredentialsProvider(provider, scope);
   return this;
 }
Example #10
0
 @Deprecated
 public static void setGlobalCredentials(String url, Credentials creds) throws HTTPException {
   assert (url != null && creds != null);
   AuthScope scope = HTTPAuthUtil.uriToAuthScope(url);
   CredentialsProvider provider = new BasicCredentialsProvider();
   provider.setCredentials(scope, creds);
   setGlobalCredentialsProvider(provider, scope);
 }
Example #11
0
  /**
   * Configure the proxy with the required credential if needed
   *
   * @param httpClientBuilder
   * @param credsProvider
   * @param url
   * @return
   * @throws java.net.MalformedURLException
   */
  private HttpClientBuilder configureProxy(
      HttpClientBuilder httpClientBuilder, CredentialsProvider credsProvider, String url)
      throws DSSException {

    try {

      if (proxyPreferenceManager == null) {
        return httpClientBuilder;
      }
      final String protocol = new URL(url).getProtocol();

      final boolean proxyHTTPS =
          Protocol.isHttps(protocol) && proxyPreferenceManager.isHttpsEnabled();
      final boolean proxyHTTP = Protocol.isHttp(protocol) && proxyPreferenceManager.isHttpEnabled();

      if (!proxyHTTPS && !proxyHTTP) {
        return httpClientBuilder;
      }

      String proxyHost = null;
      int proxyPort = 0;
      String proxyUser = null;
      String proxyPassword = null;

      if (proxyHTTPS) {
        LOG.debug("Use proxy https parameters");
        final Long port = proxyPreferenceManager.getHttpsPort();
        proxyPort = port != null ? port.intValue() : 0;
        proxyHost = proxyPreferenceManager.getHttpsHost();
        proxyUser = proxyPreferenceManager.getHttpsUser();
        proxyPassword = proxyPreferenceManager.getHttpsPassword();
      } else // noinspection ConstantConditions
      if (proxyHTTP) {
        LOG.debug("Use proxy http parameters");
        final Long port = proxyPreferenceManager.getHttpPort();
        proxyPort = port != null ? port.intValue() : 0;
        proxyHost = proxyPreferenceManager.getHttpHost();
        proxyUser = proxyPreferenceManager.getHttpUser();
        proxyPassword = proxyPreferenceManager.getHttpPassword();
      }

      if (DSSUtils.isNotEmpty(proxyUser) && DSSUtils.isNotEmpty(proxyPassword)) {
        LOG.debug("proxy user: "******":" + proxyPassword);
        AuthScope proxyAuth = new AuthScope(proxyHost, proxyPort);
        UsernamePasswordCredentials proxyCredentials =
            new UsernamePasswordCredentials(proxyUser, proxyPassword);
        credsProvider.setCredentials(proxyAuth, proxyCredentials);
      }

      LOG.debug("proxy host/port: " + proxyHost + ":" + proxyPort);
      // TODO SSL peer shut down incorrectly when protocol is https
      HttpHost proxy = new HttpHost(proxyHost, proxyPort, Protocol.HTTP.getName());
      return httpClientBuilder.setProxy(proxy);
    } catch (MalformedURLException e) {
      throw new DSSException(e);
    }
  }
 /**
  * Instantiates a new digest authentication client wrapper.
  *
  * @param hostname the hostname
  * @param port the port
  * @param scheme the scheme
  * @param username the username
  * @param password the password
  */
 public DigestAuthenticationClientWrapper(
     String hostname, int port, String scheme, String username, String password) {
   // logger.trace("==== DigestAuthenticationHttpClientWrapper ENTRY ========");
   target = new HttpHost(hostname, port, scheme);
   credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(
       new AuthScope(target.getHostName(), target.getPort()),
       new UsernamePasswordCredentials(username, password));
   logger.fine("==== DigestAuthenticationHttpClientWrapper EXIT ========");
 }
Example #13
0
 @Override
 public HttpClientContext decoratePrototypeContext(
     AuthScope scope, SiteConfig location, PasswordType type, HttpClientContext ctx) {
   if (user != null) {
     final CredentialsProvider credProvider = new BasicCredentialsProvider();
     credProvider.setCredentials(scope, new UsernamePasswordCredentials(user, pass));
     ctx.setCredentialsProvider(credProvider);
   }
   return ctx;
 }
Example #14
0
 public synchronized HttpClient getHttpClient() {
   checkDisposed();
   if (httpClient == null && authenticationInfo != null) {
     final Credentials credentials = AuthHelper.getCredentials(type, authenticationInfo);
     final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
     credentialsProvider.setCredentials(AuthScope.ANY, credentials);
     httpClient =
         HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
   }
   return httpClient;
 }
 @Override
 public void authenticate() throws CommunicationException {
   LOGGER.debug(
       "Creating credentials provider with username: '******' and password: '******'", username, password);
   CredentialsProvider credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(
       new AuthScope(getTarget().getHostName(), getTarget().getPort(), null, authScheme),
       new UsernamePasswordCredentials(username, password));
   setCredentialsProvider(credsProvider);
   super.authenticate();
 }
Example #16
0
  /**
   * Handle authentication and Proxy'ing
   *
   * @param cb
   * @throws HTTPException
   */
  protected synchronized void setAuthenticationAndProxy(HttpClientBuilder cb) throws HTTPException {
    // First, setup the ssl factory
    cb.setSSLSocketFactory(globalsslfactory);

    // Second, Construct a CredentialsProvider that is
    // the union of the Proxy credentials plus
    // either the global local credentials; local overrides global
    // Unfortunately, we cannot either clone or extract the contents
    // of the client supplied provider, so we are forced (for now)
    // to modify the client supplied provider.

    // Look in the local authcreds for best scope match
    AuthScope bestMatch = HTTPAuthUtil.bestmatch(scope, localcreds.keySet());
    CredentialsProvider cp = null;
    if (bestMatch != null) {
      cp = localcreds.get(bestMatch);
    } else {
      bestMatch = HTTPAuthUtil.bestmatch(scope, globalcreds.keySet());
      if (bestMatch != null) cp = globalcreds.get(bestMatch);
    }
    // Build the proxy credentials and AuthScope
    Credentials proxycreds = null;
    AuthScope proxyscope = null;
    if (proxyuser != null && (httpproxy != null || httpsproxy != null)) {
      if (httpproxy != null) proxyscope = HTTPAuthUtil.hostToAuthScope(httpproxy);
      else // httpsproxy != null
      proxyscope = HTTPAuthUtil.hostToAuthScope(httpsproxy);
      proxycreds = new UsernamePasswordCredentials(proxyuser, proxypwd);
    }
    if (cp == null && proxycreds != null && proxyscope != null) {
      // If client provider is null and proxycreds are not,
      // then use proxycreds alone
      cp = new BasicCredentialsProvider();
      cp.setCredentials(proxyscope, proxycreds);
    } else if (cp != null && proxycreds != null && proxyscope != null) {
      // If client provider is not null and proxycreds are not,
      // then add proxycreds to the client provider
      cp.setCredentials(proxyscope, proxycreds);
    }
    if (cp != null) this.sessioncontext.setCredentialsProvider(cp);
  }
Example #17
0
  // 获得设置代理的httpClent实例
  private CloseableHttpClient getHttpClientWithProxy(HttpProxy proxy) {
    HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
        new AuthScope(proxy.getHost(), proxy.getPort()),
        new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword()));

    return HttpClients.custom()
        .setProxy(proxyHost)
        .setDefaultCredentialsProvider(credentialsProvider)
        .build();
  }
Example #18
0
  protected HttpClient getClient() {
    Credentials defaultcreds = new UsernamePasswordCredentials(this.token, "x");
    CredentialsProvider cp = new BasicCredentialsProvider();
    cp.setCredentials(new AuthScope(getHost(), -1, AuthScope.ANY_REALM), defaultcreds);
    HttpClientBuilder clientBuilder =
        HttpClients.custom()
            .setDefaultCredentialsProvider(cp)
            .setRedirectStrategy(new LaxRedirectStrategy());

    ProxyConfiguration proxy = Hudson.getInstance().proxy;
    if (proxy != null) {
      clientBuilder.setProxy(new HttpHost(proxy.name, proxy.port));
    }

    return clientBuilder.build();
  }
Example #19
0
  /**
   * Define the Credentials
   *
   * @param httpClientBuilder
   * @param url
   * @return
   * @throws java.net.MalformedURLException
   */
  private HttpClientBuilder configCredentials(HttpClientBuilder httpClientBuilder, final String url)
      throws DSSException {

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    for (final Map.Entry<HttpHost, UsernamePasswordCredentials> entry :
        authenticationMap.entrySet()) {

      final HttpHost httpHost = entry.getKey();
      final UsernamePasswordCredentials usernamePasswordCredentials = entry.getValue();
      credsProvider.setCredentials(
          new AuthScope(httpHost.getHostName(), httpHost.getPort()), usernamePasswordCredentials);
    }
    httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
    httpClientBuilder = configureProxy(httpClientBuilder, credsProvider, url);
    return httpClientBuilder;
  }
  @Test
  @JUnitHttpServer(
      port = 9162,
      basicAuth = true,
      webapps = {@Webapp(context = "/testContext", path = "src/test/resources/test-webapp")})
  public void testBasicAuthFailure() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpUriRequest method = new HttpGet("http://localhost:9162/testContext/monkey");

    final CredentialsProvider cp = client.getCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "sucks");
    cp.setCredentials(new AuthScope("localhost", 9162), credentials);

    final HttpResponse response = client.execute(method);
    assertEquals(401, response.getStatusLine().getStatusCode());
  }
Example #21
0
  /**
   * @param argv host username password domain workstation
   * @throws IOException
   */
  public static void main(String[] argv) throws IOException {
    int status = -1;
    try {
      if (argv.length < 1) {
        return;
      }

      String path = argv[0];
      String username = "";
      String password = "";
      String domain = "";
      String workstation = "";

      if (argv.length > 2) {
        username = argv[1];
      }
      if (argv.length > 2) {
        password = argv[2];
      }

      if (argv.length > 3) {
        domain = argv[3];
      }

      if (argv.length > 4) {
        workstation = argv[4];
      }

      CloseableHttpClient client = HttpClients.createDefault();
      CredentialsProvider provider = new BasicCredentialsProvider();
      provider.setCredentials(
          AuthScope.ANY, new NTCredentials(username, password, workstation, domain));

      // HttpHost host = new HttpHost("10.130.163.112", 8081, "http");
      HttpClientContext context = HttpClientContext.create();
      context.setCredentialsProvider(provider);
      HttpGet get = new HttpGet(path);
      CloseableHttpResponse resp = client.execute(get, context);
      System.out.println(resp.getStatusLine());
      status = resp.getStatusLine().getStatusCode();
    } finally {

      System.out.println("status=" + status);
    }
  }
  private ElasticsearchClient(List<Node> nodes, String username, String password) {
    List<HttpHost> hosts = new ArrayList<>(nodes.size());
    for (Node node : nodes) {
      hosts.add(new HttpHost(node.getHost(), node.getPort(), node.getScheme().toLowerCase()));
    }
    RestClientBuilder builder = RestClient.builder(hosts.toArray(new HttpHost[hosts.size()]));

    if (username != null) {
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      credentialsProvider.setCredentials(
          AuthScope.ANY, new UsernamePasswordCredentials(username, password));
      builder.setHttpClientConfigCallback(
          httpClientBuilder ->
              httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    }

    client = builder.build();
  }
  public HttpResponse executeBinaryHttpRequest(HttpUriRequest request, int expectedStatusCode) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("kermit", "kermit");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    try {
      HttpResponse response = client.execute(request);
      Assert.assertNotNull(response.getStatusLine());
      Assert.assertEquals(expectedStatusCode, response.getStatusLine().getStatusCode());
      return response;

    } catch (ClientProtocolException e) {
      Assert.fail(e.getMessage());
    } catch (IOException e) {
      Assert.fail(e.getMessage());
    }
    return null;
  }
 protected ClientRequest newRequest(String uriString) {
   URI uri;
   try {
     uri = new URI(uriString);
   } catch (URISyntaxException e) {
     throw new RuntimeException("Malformed request URI was specified: '" + uriString + "'!", e);
   }
   if (TestConfig.isLocalServer()) {
     return new ClientRequest(uriString);
   } else {
     CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
     credentialsProvider.setCredentials(
         new AuthScope(uri.getHost(), uri.getPort()),
         new UsernamePasswordCredentials(TestConfig.getUsername(), TestConfig.getPassword()));
     HttpClient client =
         HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
     ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client);
     return new ClientRequest(uriString, executor);
   }
 }
  @Test
  @JUnitHttpServer(
      port = 9162,
      basicAuth = true,
      webapps = {@Webapp(context = "/testContext", path = "src/test/resources/test-webapp")})
  public void testBasicAuthSuccess() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpUriRequest method = new HttpGet("http://localhost:9162/testContext/monkey");

    final CredentialsProvider cp = client.getCredentialsProvider();
    final UsernamePasswordCredentials credentials =
        new UsernamePasswordCredentials("admin", "istrator");
    cp.setCredentials(new AuthScope("localhost", 9162), credentials);

    final HttpResponse response = client.execute(method);
    final String responseString = EntityUtils.toString(response.getEntity());
    LogUtils.debugf(this, "got response:\n%s", responseString);
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertTrue(responseString.contains("You are reading this from a servlet!"));
  }
  @Override
  public synchronized HttpClient getHttpClient() {
    if (myHttpClient == null) {

      PoolingHttpClientConnectionManager connectionManager =
          new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);

      // @formatter:off
      RequestConfig defaultRequestConfig =
          RequestConfig.custom()
              .setSocketTimeout(mySocketTimeout)
              .setConnectTimeout(myConnectTimeout)
              .setConnectionRequestTimeout(myConnectionRequestTimeout)
              .setStaleConnectionCheckEnabled(true)
              .setProxy(myProxy)
              .build();

      HttpClientBuilder builder =
          HttpClients.custom()
              .setConnectionManager(connectionManager)
              .setDefaultRequestConfig(defaultRequestConfig)
              .disableCookieManagement();

      if (myProxy != null
          && StringUtils.isNotBlank(myProxyUsername)
          && StringUtils.isNotBlank(myProxyPassword)) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            new AuthScope(myProxy.getHostName(), myProxy.getPort()),
            new UsernamePasswordCredentials(myProxyUsername, myProxyPassword));
        builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        builder.setDefaultCredentialsProvider(credsProvider);
      }

      myHttpClient = builder.build();
      // @formatter:on

    }

    return myHttpClient;
  }
Example #27
0
  protected static ClientConfig getClientConfig(
      final Type type,
      final AuthenticationInfo authenticationInfo,
      final boolean includeProxySettings) {
    final Credentials credentials = AuthHelper.getCredentials(type, authenticationInfo);

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    final ConnectorProvider connectorProvider = new ApacheConnectorProvider();

    final ClientConfig clientConfig = new ClientConfig().connectorProvider(connectorProvider);
    clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);

    clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
    clientConfig.property(
        ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    // Define fiddler as a local HTTP proxy
    if (includeProxySettings) {
      final String proxyHost;
      if (System.getProperty("proxyHost") != null) {
        proxyHost = System.getProperty("proxyHost");
      } else {
        proxyHost = "127.0.0.1";
      }

      final String proxyPort;
      if (System.getProperty("proxyPort") != null) {
        proxyPort = System.getProperty("proxyPort");
      } else {
        proxyPort = "8888";
      }

      final String proxyUrl = String.format("http://%s:%s", proxyHost, proxyPort);

      clientConfig.property(ClientProperties.PROXY_URI, proxyUrl);
      clientConfig.property(ApacheClientProperties.SSL_CONFIG, getSslConfigurator());
    }
    return clientConfig;
  }
Example #28
0
  public static void performHTTPRequest(String url) {
    try {
      HttpGet getMethod = new HttpGet(url);
      HttpClientBuilder clientBuilder = HttpClientBuilder.create();

      String[] userPassword = url.split("@")[0].replace("http://", "").split(":");

      CredentialsProvider credsProvider = new BasicCredentialsProvider();
      credsProvider.setCredentials(
          new AuthScope(getMethod.getURI().getHost(), getMethod.getURI().getPort()),
          new UsernamePasswordCredentials(userPassword[0], userPassword[1]));
      clientBuilder.setDefaultCredentialsProvider(credsProvider);
      HttpClient httpClient = clientBuilder.build();

      httpClient.execute(getMethod);

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #29
0
  @Override
  protected String doInBackground(String... params) {
    if (params.length > 0) {
      String url = params[0];
      String username = params[1];
      String password = params[2];

      try {

        AndroidHttpClient httpClient = AndroidHttpClient.newInstance("ExceedVote connection");

        URL urlObj = new URL(url);
        HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
        AuthScope scope = new AuthScope(urlObj.getHost(), urlObj.getPort());
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

        CredentialsProvider cp = new BasicCredentialsProvider();
        cp.setCredentials(scope, creds);
        HttpContext credContext = new BasicHttpContext();
        credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp);

        HttpGet job = new HttpGet(url);
        HttpResponse response = httpClient.execute(host, job, credContext);
        StatusLine status = response.getStatusLine();
        Log.d("TAG", status.getStatusCode() + "");
        if (status.getStatusCode() != 200) {
          Log.d("ERROR", EntityUtils.toString(response.getEntity()));
          return "error";
        }
        HttpEntity entity = response.getEntity();
        String s_response = EntityUtils.toString(entity);
        httpClient.close();
        return s_response;
      } catch (Exception e) {
        Log.d("TAG", e.getMessage());
        return "error";
      }
    }
    return "error";
  }
Example #30
0
  public Session(
      URL url, String login, String password, boolean trustSelfSigned, int maxConnections) {

    _executorService = Executors.newFixedThreadPool(maxConnections);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    credentialsProvider.setCredentials(
        new AuthScope(url.getHost(), url.getPort()),
        new UsernamePasswordCredentials(login, password));

    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    httpClientBuilder.setMaxConnPerRoute(maxConnections);
    httpClientBuilder.setMaxConnTotal(maxConnections);
    httpClientBuilder.setRoutePlanner(_getHttpRoutePlanner());

    if (trustSelfSigned) {
      try {
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

        SSLConnectionSocketFactory sslConnectionSocketFactory =
            new SSLConnectionSocketFactory(
                sslContextBuilder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
      } catch (Exception e) {
        _logger.error(e.getMessage(), e);
      }
    }

    _httpClient = httpClientBuilder.build();

    _httpHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
  }