Beispiel #1
0
 /** Creates the client executor that will be used by RESTEasy when making the request. */
 private ClientExecutor createClientExecutor() {
   // TODO I think the http client is thread safe - so let's try to create just one of these
   DefaultHttpClient httpClient = new DefaultHttpClient();
   httpClient.addRequestInterceptor(
       new HttpRequestInterceptor() {
         @Override
         public void process(HttpRequest request, HttpContext context)
             throws HttpException, IOException {
           Locale l = getLocale();
           if (l == null) {
             l = Locale.getDefault();
           }
           request.addHeader("Accept-Language", l.toString()); // $NON-NLS-1$
         }
       });
   if (this.authProvider != null) {
     httpClient.addRequestInterceptor(
         new HttpRequestInterceptor() {
           @Override
           public void process(HttpRequest request, HttpContext context)
               throws HttpException, IOException {
             authProvider.provideAuthentication(request);
           }
         });
   }
   return new ApacheHttpClient4Executor(httpClient);
 }
  /**
   * new {@link DefaultHttpClient}, and set strategy.
   *
   * @return DefaultHttpClient
   */
  private DefaultHttpClient createApacheHttpClient(BasicHttpParams httpParams) {
    DefaultHttpClient httpClient =
        new DefaultHttpClient(createClientConnManager(httpParams), httpParams);
    // disable apache default redirect handler
    httpClient.setRedirectHandler(
        new RedirectHandler() {

          @Override
          public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
            return false;
          }

          @Override
          public URI getLocationURI(HttpResponse response, HttpContext context)
              throws ProtocolException {
            return null;
          }
        });
    // disable apache default retry handler
    httpClient.setHttpRequestRetryHandler(
        new HttpRequestRetryHandler() {
          @Override
          public boolean retryRequest(
              IOException exception, int executionCount, HttpContext context) {
            return false;
          }
        });
    // enable gzip supporting in request
    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          @Override
          public void process(org.apache.http.HttpRequest request, HttpContext context) {
            if (!request.containsHeader(Consts.HEADER_ACCEPT_ENCODING)) {
              request.addHeader(Consts.HEADER_ACCEPT_ENCODING, Consts.ENCODING_GZIP);
            }
          }
        });
    // enable gzip supporting in response
    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          @Override
          public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
              return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase(Consts.ENCODING_GZIP)) {
                  response.setEntity(new GZIPEntityWrapper(entity));
                  break;
                }
              }
            }
          }
        });
    // setKeepAlive(httpClient);
    return httpClient;
  }
 private HttpClient createHttpClient(String userId, String password) {
   DefaultHttpClient retval = createDefaultHttpClient();
   Credentials defaultcreds = new UsernamePasswordCredentials(userId, password);
   retval.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);
   retval.addRequestInterceptor(sm_preemptiveAuth, 0);
   return retval;
 }
Beispiel #4
0
  public HttpUtils(int connTimeout, String userAgent) {
    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connTimeout);
    HttpConnectionParams.setSoTimeout(params, connTimeout);
    HttpConnectionParams.setConnectionTimeout(params, connTimeout);

    if (TextUtils.isEmpty(userAgent)) {
      userAgent = OtherUtils.getUserAgent(null);
    }
    HttpProtocolParams.setUserAgent(params, userAgent);

    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));
    ConnManagerParams.setMaxTotalConnections(params, 10);

    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 1024 * 8);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", DefaultSSLSocketFactory.getSocketFactory(), 443));

    httpClient =
        new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES));

    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          @Override
          public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext)
              throws org.apache.http.HttpException, IOException {
            if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {
              httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
          }
        });

    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          @Override
          public void process(HttpResponse response, HttpContext httpContext)
              throws org.apache.http.HttpException, IOException {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
              return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase("gzip")) {
                  response.setEntity(new GZipDecompressingEntity(response.getEntity()));
                  return;
                }
              }
            }
          }
        });
  }
  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);
    }
  }
Beispiel #6
0
    public org.apache.http.client.HttpClient configureClient() {
      HttpParams params = new BasicHttpParams();
      HttpProtocolParams.setUseExpectContinue(params, useExpectContinue);
      HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
      HttpConnectionParams.setSoTimeout(params, socketTimeout);
      HttpConnectionParams.setTcpNoDelay(params, Boolean.TRUE);

      String protocol = "http";

      if (enableSSL) protocol = "https";

      params.setParameter(ClientPNames.DEFAULT_HOST, new HttpHost(host, port, protocol));
      if (proxy != null) {
        params.setParameter(
            ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxy, proxyPort, protocol));
      }
      DefaultHttpClient client = new DefaultHttpClient(configureConnectionManager(params), params);
      if (username != null && password != null) {
        client
            .getCredentialsProvider()
            .setCredentials(
                new AuthScope(host, port, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(username, password));
        client.addRequestInterceptor(new PreemptiveAuthRequestInterceptor(), 0);
      }

      return client;
    }
Beispiel #7
0
  /** Creates a new AsyncHttpClient. */
  public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(
        httpParams,
        String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
              request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
              request.addHeader(header, clientHeaderMap.get(header));
            }
          }
        });

    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                  response.setEntity(new InflatingEntity(response.getEntity()));
                  break;
                }
              }
            }
          }
        });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
  }
  private void configureCredentials(
      DefaultHttpClient httpClient, Collection<Authentication> authentications) {
    if (authentications != null && authentications.size() > 0) {
      useCredentials(httpClient, AuthScope.ANY_HOST, AuthScope.ANY_PORT, authentications);

      // Use preemptive authorisation if no other authorisation has been established
      httpClient.addRequestInterceptor(new PreemptiveAuth(new BasicScheme()), 0);
    }
  }
Beispiel #9
0
  public Http(Context context) {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, 10);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
              request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
              request.addHeader(header, clientHeaderMap.get(header));
            }
          }
        });

    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
              return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                  response.setEntity(new InflatingEntity(response.getEntity()));
                  break;
                }
              }
            }
          }
        });

    clientHeaderMap = new HashMap<String, String>();
  }
Beispiel #10
0
  /**
   * 获得没有任何设置的实例
   *
   * @return
   */
  public static HttpClient getCleanHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient(getHttpParams());
    // httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
    // new HttpHost("localhost", 8888));

    httpClient.addRequestInterceptor(getRequestInter());
    httpClient.addResponseInterceptor(getResponseInter());
    httpClient.setHttpRequestRetryHandler(buildMyRetryHandler());

    return httpClient;
  }
Beispiel #11
0
 @Override
 public void initialize(DefaultHttpClient httpClient) throws ClientServicesException {
   try {
     AccessToken token = oaProvider.acquireToken(false);
     if (token != null) {
       HttpRequestInterceptor oauthInterceptor = new OAuthInterceptor(token);
       httpClient.addRequestInterceptor(oauthInterceptor, 0);
     }
   } catch (OAuthException ex) {
     throw new ClientServicesException(ex);
   }
 }
 /**
  * Configures the httpClient to connect to the URL provided.
  *
  * @param authToken
  */
 private static DefaultHttpClient getHttpClient() {
   DefaultHttpClient httpClient = new DefaultHttpClient();
   final HttpParams params = httpClient.getParams();
   HttpConnectionParams.setConnectionTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
   HttpConnectionParams.setSoTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
   ConnManagerParams.setTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
   HttpClientParams.setRedirecting(params, false);
   HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
   httpClient.addRequestInterceptor(new DumpHeadersRequestInterceptor());
   httpClient.addResponseInterceptor(new DumpHeadersResponseInterceptor());
   httpClient.addResponseInterceptor(new CookieQuotesFixerResponseInterceptor());
   return httpClient;
 }
 /* (non-Javadoc)
  * @see java.net.URLConnection#connect()
  */
 @Override
 public void connect() throws IOException {
   if (m_client != null) {
     return;
   }
   final HttpParams httpParams = new BasicHttpParams();
   if (m_request != null) {
     int timeout = m_request.getParameterAsInt("timeout");
     if (timeout > 0) {
       HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
       HttpConnectionParams.setSoTimeout(httpParams, timeout);
     }
   }
   m_client = new DefaultHttpClient(httpParams);
   m_client.addRequestInterceptor(new RequestAcceptEncoding());
   m_client.addResponseInterceptor(new ResponseContentEncoding());
   if (m_request != null) {
     int retries = m_request.getParameterAsInt("retries");
     if (retries > 0) {
       m_client.setHttpRequestRetryHandler(
           new DefaultHttpRequestRetryHandler() {
             @Override
             public boolean retryRequest(
                 IOException exception, int executionCount, HttpContext context) {
               if (executionCount <= getRetryCount()
                   && (exception instanceof SocketTimeoutException
                       || exception instanceof ConnectTimeoutException)) {
                 return true;
               }
               return super.retryRequest(exception, executionCount, context);
             }
           });
     }
     String disableSslVerification = m_request.getParameter("disable-ssl-verification");
     if (Boolean.parseBoolean(disableSslVerification)) {
       final SchemeRegistry registry = m_client.getConnectionManager().getSchemeRegistry();
       final Scheme https = registry.getScheme("https");
       try {
         SSLSocketFactory factory =
             new SSLSocketFactory(
                 SSLContext.getInstance(EmptyKeyRelaxedTrustSSLContext.ALGORITHM),
                 SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
         final Scheme lenient = new Scheme(https.getName(), https.getDefaultPort(), factory);
         registry.register(lenient);
       } catch (NoSuchAlgorithmException e) {
         LOG.warn(e.getMessage());
       }
     }
   }
 }
  public static void configureWithPreemptiveBasicAuth(
      DefaultHttpClient client, String username, String passsword) {
    //
    // create a new request interceptor that includes adding basic auth
    //
    PreemptiveBasicAuthHttpRequestInterceptor interceptor =
        new PreemptiveBasicAuthHttpRequestInterceptor();

    // set credentials
    interceptor.setCredentials(username, passsword);

    // add as the first request interceptor
    client.addRequestInterceptor(interceptor, 0);
  }
Beispiel #15
0
  /**
   * 获得连接池的实例
   *
   * @return
   */
  public static HttpClient getCoonPoolHttpClient() {

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setMaxTotal(800);
    cm.setDefaultMaxPerRoute(200);

    DefaultHttpClient httpClient = new DefaultHttpClient(cm, getHttpParams());

    httpClient.addRequestInterceptor(getRequestInter());
    httpClient.addResponseInterceptor(getResponseInter());
    httpClient.setHttpRequestRetryHandler(buildMyRetryHandler());

    return httpClient;
  }
  @Override
  protected void accessToken(final DefaultHttpClient client) throws OAuth2Exception {
    client.addRequestInterceptor(
        new HttpRequestInterceptor() {

          @Override
          public void process(final HttpRequest request, final HttpContext context)
              throws HttpException, IOException {
            request.removeHeaders(HttpHeaders.AUTHORIZATION);
            request.addHeader(
                HttpHeaders.AUTHORIZATION, OAuthClientUtils.createAuthorizationHeader(accessToken));
          }
        });
  }
  private static HttpClient setupHttpClient(boolean gzip) {
    SSLSocketFactory.getSocketFactory()
        .setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(20));
    params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 200);
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    DefaultHttpClient httpClient = new DefaultHttpClient(cm, new BasicHttpParams());
    httpClient.setHttpRequestRetryHandler(
        new DefaultHttpRequestRetryHandler(HTTP_RETRY_COUNT, true));

    if (gzip) {
      httpClient.addRequestInterceptor(
          new HttpRequestInterceptor() {
            public void process(HttpRequest request, HttpContext context)
                throws HttpException, IOException {
              if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
              }
            }
          });

      httpClient.addResponseInterceptor(
          new HttpResponseInterceptor() {
            public void process(HttpResponse response, HttpContext context)
                throws HttpException, IOException {
              HttpEntity entity = response.getEntity();
              Header ceheader = entity.getContentEncoding();
              if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (int i = 0; i < codecs.length; i++) {
                  if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                    response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                    return;
                  }
                }
              }
            }
          });
    }

    return httpClient;
  }
    private static DefaultHttpClient setupHttpClient() {
      HttpParams connectionParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(connectionParams, 30000); // thirty seconds
      HttpConnectionParams.setSoTimeout(connectionParams, 30000);
      HttpClientParams.setRedirecting(connectionParams, false);
      DefaultHttpClient client = new DefaultHttpClient(connectionParams);

      client.addRequestInterceptor(
          new HttpRequestInterceptor() {
            public void process(HttpRequest request, HttpContext context) {
              if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
              }
            }
          });

      return client;
    }
  public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope("localhost", 80),
            new UsernamePasswordCredentials("username", "password"));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    httpclient.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpHost targetHost = new HttpHost("localhost", 80, "http");

    HttpGet httpget = new HttpGet("/");

    System.out.println("executing request: " + httpget.getRequestLine());
    System.out.println("to target: " + targetHost);

    for (int i = 0; i < 3; i++) {
      HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
      HttpEntity entity = response.getEntity();

      System.out.println("----------------------------------------");
      System.out.println(response.getStatusLine());
      if (entity != null) {
        System.out.println("Response content length: " + entity.getContentLength());
        entity.consumeContent();
      }
    }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
  }
Beispiel #20
0
  public void setBasicAuthCredentials(String login, String password, String scope) {
    getHttpClient();

    httpClient
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(scope, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(login, password));

    httpContext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    httpContext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    httpClient.addRequestInterceptor(new ForcePreemptiveAuth(), 0);
  }
  protected void initAuthentication() {
    if (registration.getAuthenticationMechanism() != null) {
      if (registration.getAuthenticationMechanism().getType() instanceof BasicAuth) {
        BasicAuth basic = (BasicAuth) registration.getAuthenticationMechanism().getType();
        UsernamePasswordCredentials creds =
            new UsernamePasswordCredentials(basic.getUsername(), basic.getPassword());
        AuthScope authScope = new AuthScope(AuthScope.ANY);
        ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(authScope, creds);

        localContext = new BasicHttpContext();

        // Generate BASIC scheme object and stick it to the local execution context
        BasicScheme basicAuth = new BasicScheme();
        localContext.setAttribute("preemptive-auth", basicAuth);

        // Add as the first request interceptor
        ((DefaultHttpClient) client).addRequestInterceptor(new PreemptiveAuth(), 0);
        executor.setHttpContext(localContext);
      }
    }
  }
Beispiel #22
0
  /** create and init the client for your jenkins host with configured credentials */
  public void initClient() {
    // Create your httpclient
    client = new DefaultHttpClient();

    // Then provide the right credentials
    client
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    // Generate BASIC scheme object and stick it to the execution context
    BasicScheme basicAuth = new BasicScheme();
    context = new BasicHttpContext();
    context.setAttribute("preemptive-auth", basicAuth);

    // Add as the first (because of the zero) request interceptor
    // It will first intercept the request and preemptively initialize the authentication scheme if
    // there is not
    client.addRequestInterceptor(new PreemptiveAuth(), 0);
  }
Beispiel #23
0
  public String doPost(
      String host, int port, String uri, HashMap<String, String> paraMap, String charset)
      throws IOException {
    UrlEncodedFormEntity entity = genEntity(paraMap, charset);

    HttpPost httppost = new HttpPost("http://" + host + ":" + port + uri);
    httppost.setEntity(entity);

    httpclient
        .getCredentialsProvider()
        .setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(usname, passwd));

    // *
    BasicScheme basicAuth = new BasicScheme();
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    httpclient.addRequestInterceptor((HttpRequestInterceptor) new PreemptiveAuth(), 0);

    HttpResponse response = httpclient.execute(httppost, localcontext);
    // */
    // HttpResponse response = httpclient.execute(httppost);

    if (response.getStatusLine().toString().indexOf("401") >= 0) {
      throw new RuntimeException("Authorization is denied!");
    }
    HttpEntity res_entity = response.getEntity();

    if (res_entity != null) {
      InputStream is = res_entity.getContent();
      BufferedReader in = new BufferedReader(new InputStreamReader(is));
      StringBuffer buffer = new StringBuffer();
      String line = "";
      while ((line = in.readLine()) != null) {
        buffer.append(line.trim());
      }
      return buffer.toString();
    }
    return null;
  }
  public HttpClient getAuthorizedClient(String hostName, int port) {
    DefaultHttpClient client = new DefaultHttpClient();
    client.addRequestInterceptor(new ShopifyRequestInterceptor());
    client.addResponseInterceptor(
        new HttpResponseInterceptor() {
          public void process(HttpResponse response, HttpContext context)
              throws HttpException, IOException {
            /* CRest 1.0.1 throws an exception is the status code != 200,
             * even on 201 Created, just translate all 200 responses to error code 200. */
            int code = response.getStatusLine().getStatusCode();
            if (code >= 200 && code < 300) {
              response.setStatusCode(200);
            }
          }
        });
    AuthScope scope = new AuthScope(hostName, port);
    UsernamePasswordCredentials creds =
        new UsernamePasswordCredentials(credential.getApiKey(), credential.getPassword());
    client.getCredentialsProvider().setCredentials(scope, creds);

    return client;
  }
Beispiel #25
0
  public HttpUtils(String baseURL, String username, String password) throws Exception {
    try {
      URL url = new URL(baseURL);

      client = new DefaultHttpClient();
      basicAuth = new BasicScheme();
      httpContext = new BasicHttpContext();
      httpHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

      if (username != null && password != null) {
        httpContext.setAttribute("preemptive-auth", basicAuth);

        // Add as the first request interceptor
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
        AuthScope authScope = new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM);
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        client.getCredentialsProvider().setCredentials(authScope, credentials);
      }
    } catch (Exception e) {
      logger.error("Failed to instantiate HttpUtils.", e);
      throw e;
    }
  }
 /* (non-Javadoc)
  * @see java.net.URLConnection#connect()
  */
 @Override
 public void connect() throws IOException {
   if (m_client != null) {
     return;
   }
   m_client = new DefaultHttpClient();
   m_client.addRequestInterceptor(
       new HttpRequestInterceptor() {
         @Override
         public void process(HttpRequest request, HttpContext context)
             throws HttpException, IOException {
           if (!request.containsHeader("Accept-Encoding")) {
             request.addHeader("Accept-Encoding", "gzip");
           }
         }
       });
   m_client.addResponseInterceptor(
       new HttpResponseInterceptor() {
         public void process(final HttpResponse response, final HttpContext context)
             throws HttpException, IOException {
           HttpEntity entity = response.getEntity();
           if (entity != null) {
             Header ceheader = entity.getContentEncoding();
             if (ceheader != null) {
               HeaderElement[] codecs = ceheader.getElements();
               for (int i = 0; i < codecs.length; i++) {
                 if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                   response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                   return;
                 }
               }
             }
           }
         }
       });
 }
Beispiel #27
0
  public RequestExecutor execute(Request r) throws ClientProtocolException, IOException {
    clear();
    r.customizeIfNeeded();
    request = r.getRequest();

    // Optionally setup for basic authentication
    if (r.getUsername() != null) {
      httpClient
          .getCredentialsProvider()
          .setCredentials(
              AuthScope.ANY, new UsernamePasswordCredentials(r.getUsername(), r.getPassword()));

      // And add request interceptor to have preemptive authentication
      httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);
    } else {
      // Make sure existing credentials are not reused - but looks like we
      // cannot set null as credentials
      httpClient
          .getCredentialsProvider()
          .setCredentials(
              AuthScope.ANY,
              new UsernamePasswordCredentials(getClass().getName(), getClass().getSimpleName()));
      httpClient.removeRequestInterceptorByClass(PreemptiveAuthInterceptor.class);
    }

    // Setup redirects
    httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, r.getRedirects());

    // Execute request
    response = httpClient.execute(request);
    entity = response.getEntity();
    if (entity != null) {
      consumeEntity();
    }
    return this;
  }
  public Host(
      String server,
      String rootPath,
      Integer port,
      String user,
      String password,
      ProxyDetails proxyDetails,
      int timeoutMillis,
      Cache<Folder, List<Resource>> cache,
      FileSyncer fileSyncer) {
    super(
        (cache != null
            ? cache
            : new MemoryCache<Folder, List<Resource>>("resource-cache-default", 50, 20)));
    if (server == null) {
      throw new IllegalArgumentException("host name cannot be null");
    }
    this.rootPath = rootPath;
    this.timeout = timeoutMillis;
    this.server = server;
    this.port = port;
    this.user = user;
    this.password = password;
    client = new DefaultHttpClient();
    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 10000);
    HttpConnectionParams.setSoTimeout(params, 10000);

    if (user != null) {
      client
          .getCredentialsProvider()
          .setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
      PreemptiveAuthInterceptor interceptor = new PreemptiveAuthInterceptor();
      client.addRequestInterceptor(interceptor);
    }

    HttpRequestRetryHandler handler = new DefaultHttpRequestRetryHandler(0, false);
    client.setHttpRequestRetryHandler(handler);

    if (proxyDetails != null) {
      if (proxyDetails.isUseSystemProxy()) {
        System.setProperty("java.net.useSystemProxies", "true");
      } else {
        System.setProperty("java.net.useSystemProxies", "false");
        if (proxyDetails.getProxyHost() != null && proxyDetails.getProxyHost().length() > 0) {
          HttpHost proxy =
              new HttpHost(proxyDetails.getProxyHost(), proxyDetails.getProxyPort(), "http");
          client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
          if (proxyDetails.hasAuth()) {
            client
                .getCredentialsProvider()
                .setCredentials(
                    new AuthScope(proxyDetails.getProxyHost(), proxyDetails.getProxyPort()),
                    new UsernamePasswordCredentials(
                        proxyDetails.getUserName(), proxyDetails.getPassword()));
          }
        }
      }
    }
    transferService = new TransferService(client, connectionListeners);
    transferService.setTimeout(timeoutMillis);
    this.fileSyncer = fileSyncer;
  }
  /**
   * {@inheritDoc} <br>
   * <br>
   * The default implementation does all of this and more, including using a connection pool and
   * killing connections after a timeout to use less battery power on mobile devices. It's unlikely
   * that you'll want to change this behavior.
   */
  @Override
  public synchronized HttpClient getHttpClient() {
    if (client == null) {
      // Set up default connection params. There are two routes to
      // Dropbox - api server and content server.
      HttpParams connParams = new BasicHttpParams();
      ConnManagerParams.setMaxConnectionsPerRoute(
          connParams,
          new ConnPerRoute() {
            @Override
            public int getMaxForRoute(HttpRoute route) {
              return 10;
            }
          });
      ConnManagerParams.setMaxTotalConnections(connParams, 20);

      // Set up scheme registry.
      SchemeRegistry schemeRegistry = new SchemeRegistry();
      schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

      DBClientConnManager cm = new DBClientConnManager(connParams, schemeRegistry);

      try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(
            null,
            new TrustManager[] {
              new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                  System.out.println("getAcceptedIssuers =============");
                  return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                  System.out.println("checkClientTrusted =============");
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                  System.out.println("checkServerTrusted =============");
                }
              }
            },
            new SecureRandom());
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", 443, sf);
        schemeRegistry.register(httpsScheme);
      } catch (Exception e) {
        e.printStackTrace();
      }
      schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

      // Set up client params.
      HttpParams httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_TIMEOUT_MILLIS);
      HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_TIMEOUT_MILLIS);
      HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
      HttpProtocolParams.setUserAgent(
          httpParams, "OfficialDropboxJavaSDK/" + DropboxAPI.SDK_VERSION);

      DefaultHttpClient c =
          new DefaultHttpClient(cm, httpParams) {
            @Override
            protected ConnectionKeepAliveStrategy createConnectionKeepAliveStrategy() {
              return new DBKeepAliveStrategy();
            }

            @Override
            protected ConnectionReuseStrategy createConnectionReuseStrategy() {
              return new DBConnectionReuseStrategy();
            }
          };

      c.addRequestInterceptor(
          new HttpRequestInterceptor() {
            @Override
            public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
              if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
              }
            }
          });

      c.addResponseInterceptor(
          new HttpResponseInterceptor() {
            @Override
            public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
              HttpEntity entity = response.getEntity();
              if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                  HeaderElement[] codecs = ceheader.getElements();
                  for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                      response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                      return;
                    }
                  }
                }
              }
            }
          });

      client = c;
    }

    return client;
  }
Beispiel #30
0
  /** {@inheritDoc} */
  @Override
  public PollStatus poll(MonitoredService svc, Map<String, Object> map) {
    PollStatus pollStatus = PollStatus.unresponsive();
    DefaultHttpClient httpClient = new DefaultHttpClient();

    try {
      final String hostAddress = InetAddressUtils.str(svc.getAddress());

      URIBuilder ub = new URIBuilder();
      ub.setScheme(ParameterMap.getKeyedString(map, "scheme", DEFAULT_SCHEME));
      ub.setHost(hostAddress);
      ub.setPort(ParameterMap.getKeyedInteger(map, "port", DEFAULT_PORT));
      ub.setPath(ParameterMap.getKeyedString(map, "path", DEFAULT_PATH));
      HttpGet getMethod = new HttpGet(ub.build());
      httpClient
          .getParams()
          .setIntParameter(
              CoreConnectionPNames.CONNECTION_TIMEOUT,
              ParameterMap.getKeyedInteger(map, "timeout", DEFAULT_TIMEOUT));
      httpClient
          .getParams()
          .setIntParameter(
              CoreConnectionPNames.SO_TIMEOUT,
              ParameterMap.getKeyedInteger(map, "timeout", DEFAULT_TIMEOUT));
      httpClient
          .getParams()
          .setParameter(
              CoreProtocolPNames.USER_AGENT,
              ParameterMap.getKeyedString(map, "user-agent", DEFAULT_USER_AGENT));

      // Set the virtual host to the 'virtual-host' parameter or the host address if 'virtual-host'
      // is not present
      getMethod
          .getParams()
          .setParameter(
              ClientPNames.VIRTUAL_HOST,
              new HttpHost(
                  ParameterMap.getKeyedString(map, "virtual-host", hostAddress),
                  ParameterMap.getKeyedInteger(map, "port", DEFAULT_PORT)));

      if (ParameterMap.getKeyedBoolean(map, "http-1.0", false)) {
        httpClient
            .getParams()
            .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
      }

      for (Object okey : map.keySet()) {
        String key = okey.toString();
        if (key.matches("header_[0-9]+$")) {
          String headerName = ParameterMap.getKeyedString(map, key, null);
          String headerValue = ParameterMap.getKeyedString(map, key + "_value", null);
          getMethod.setHeader(headerName, headerValue);
        }
      }

      if (ParameterMap.getKeyedBoolean(map, "auth-enabled", false)) {
        httpClient
            .getCredentialsProvider()
            .setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials(
                    ParameterMap.getKeyedString(map, "auth-user", DEFAULT_USER),
                    ParameterMap.getKeyedString(map, "auth-password", DEFAULT_PASSWORD)));
        if (ParameterMap.getKeyedBoolean(map, "auth-preemptive", true)) {
          /**
           * Add an HttpRequestInterceptor that will perform preemptive auth
           *
           * @see http://hc.apache.org/httpcomponents-client-4.0.1/tutorial/html/authentication.html
           */
          HttpRequestInterceptor preemptiveAuth =
              new HttpRequestInterceptor() {

                public void process(final HttpRequest request, final HttpContext context)
                    throws IOException {

                  AuthState authState =
                      (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                  CredentialsProvider credsProvider =
                      (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
                  HttpHost targetHost =
                      (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                  // If not auth scheme has been initialized yet
                  if (authState.getAuthScheme() == null) {
                    AuthScope authScope =
                        new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    // Obtain credentials matching the target host
                    Credentials creds = credsProvider.getCredentials(authScope);
                    // If found, generate BasicScheme preemptively
                    if (creds != null) {
                      authState.update(new BasicScheme(), creds);
                    }
                  }
                }
              };
          httpClient.addRequestInterceptor(preemptiveAuth, 0);
        }
      }

      log().debug("httpClient request with the following parameters: " + httpClient);
      log().debug("getMethod parameters: " + getMethod);
      HttpResponse response = httpClient.execute(getMethod);
      int statusCode = response.getStatusLine().getStatusCode();
      String statusText = response.getStatusLine().getReasonPhrase();
      String expectedText = ParameterMap.getKeyedString(map, "response-text", null);

      log().debug("returned results are:");

      if (!inRange(
          ParameterMap.getKeyedString(map, "response-range", DEFAULT_HTTP_STATUS_RANGE),
          statusCode)) {
        pollStatus = PollStatus.unavailable(statusText);
      } else {
        pollStatus = PollStatus.available();
      }

      if (expectedText != null) {
        String responseText = EntityUtils.toString(response.getEntity());
        if (expectedText.charAt(0) == '~') {
          if (!responseText.matches(expectedText.substring(1))) {
            pollStatus = PollStatus.unavailable("Regex Failed");
          } else pollStatus = PollStatus.available();
        } else {
          if (expectedText.equals(responseText)) pollStatus = PollStatus.available();
          else pollStatus = PollStatus.unavailable("Did not find expected Text");
        }
      }

    } catch (IOException e) {
      log().info(e.getMessage());
    } catch (URISyntaxException e) {
      log().info(e.getMessage());
    } finally {
      if (httpClient != null) {
        httpClient.getConnectionManager().shutdown();
      }
    }
    return pollStatus;
  }