protected @Nonnull HttpClient getClient(String url, boolean multipart) throws InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
      throw new InternalException("No context was specified for this request");
    }
    boolean ssl = url.startsWith("https");
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    if (!multipart) {
      HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    }
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
      String proxyHost = p.getProperty("proxyHost");
      String proxyPort = p.getProperty("proxyPort");

      if (proxyHost != null) {
        int port = 0;

        if (proxyPort != null && proxyPort.length() > 0) {
          port = Integer.parseInt(proxyPort);
        }
        params.setParameter(
            ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http"));
      }
    }
    return new DefaultHttpClient(params);
  }
Example #2
0
 /**
  * Constructor will setup httpclient, post request method and useragent information as required
  */
 public httpPOST() {
   httpclient = new DefaultHttpClient();
   System.setProperty("http.agent", "");
   httppost = new HttpPost(speechAPIURL);
   HttpProtocolParams.setUserAgent(httpclient.getParams(), User_Agent);
   httppost.setHeader(HeaderType, HeaderContent);
 }
  /**
   * Create a new HttpClient with reasonable defaults (which you can update).
   *
   * @param userAgent to report in your HTTP requests.
   * @return FailfastHttpClient for you to use for all your requests.
   */
  public static FailfastHttpClient newInstance(String userAgent) {
    HttpParams params = new BasicHttpParams();

    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 10 seconds.  Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, READ_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller.  Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Set the specified user agent and register standard protocols.
    if (userAgent != null) HttpProtocolParams.setUserAgent(params, userAgent);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager manager = new HackThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new FailfastHttpClient(manager, params);
  }
  public void post(FileEntity fileEntity) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(fileEntity);

    HttpParams params = httpPost.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, DEFAULT_USER_AGENT);

    try {

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpPost);

      if (response.getStatusLine().getStatusCode() < 200
          || response.getStatusLine().getStatusCode() >= 300)
        throw new IOException(
            "bad status code, upload file " + response.getStatusLine().getStatusCode());

    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new IOException("Http error: " + e.getMessage());
    } finally {
      //
    }
  }
 private HttpClient getHttpClient() {
   if (null == customerHttpClient) {
     HttpParams params = new BasicHttpParams();
     // 设置一些基本参数
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
     HttpProtocolParams.setUseExpectContinue(params, true);
     HttpProtocolParams.setUserAgent(params, "Linux; Android 2.2.1;zh-CN; itkt_Android");
     //			HttpClientParams.setRedirecting(params, true);
     //		    HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
     // 设置最大连接数
     ConnManagerParams.setMaxTotalConnections(params, MAX_TOTAL_CONNECTIONS);
     // 设置获取连接的最大等待时间
     ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
     // 设置每个路由最大连接数
     ConnPerRouteBean connPerRoute = new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS);
     ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
     // 设置连接超时时间
     HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
     // 设置读取超时时间
     HttpConnectionParams.setSoTimeout(params, READ_TIMEOUT);
     try {
       KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
       SchemeRegistry schReg = new SchemeRegistry();
       schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
       // 使用线程安全的连接管理来创建HttpClient
       ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
       customerHttpClient = new DefaultHttpClient(conMgr, params);
       customerHttpClient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return customerHttpClient;
 }
Example #6
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;
                }
              }
            }
          }
        });
  }
    /**
     * Static method to initialize HTTP client. Notice the double instance == null check. By
     * checking in and outside of the synchronization, this method is threadsafe. It ensures the
     * singleton is only instantiated once.
     *
     * @return
     */
    public HttpClient getInstance() {
      if (INSTANCE == null) {
        synchronized (HttpConnectionManager.class) {
          if (INSTANCE == null) {
            final HttpParams params = new BasicHttpParams();
            final SchemeRegistry registry = new SchemeRegistry();
            final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();

            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "utf-8");
            HttpProtocolParams.setUserAgent(params, "Basedroid");

            sslSocketFactory.setHostnameVerifier(
                SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sslSocketFactory, 443));

            final ClientConnectionManager manager =
                new ThreadSafeClientConnManager(params, registry);
            INSTANCE = new DefaultHttpClient(manager, params);
          }
        }
      }
      return INSTANCE;
    }
Example #8
0
  public static synchronized HttpClient getHttpClient() {
    if (null == customerHttpClient) {
      HttpParams params = new BasicHttpParams();
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params, CHARSET);
      HttpProtocolParams.setUseExpectContinue(params, true);
      HttpProtocolParams.setUserAgent(
          params,
          "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
              + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");

      // 从连接池中取连续的超时时间
      ConnManagerParams.setTimeout(params, 1000);
      HttpConnectionParams.setConnectionTimeout(params, 2000);
      HttpConnectionParams.setSoTimeout(params, 4000);

      // 设置我们的HttpClient支持HTTP和HTTPS两种模式
      SchemeRegistry schReg = new SchemeRegistry();
      schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

      // 使用线程安全的连接管理来创建HttpClient
      ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
      customerHttpClient = new DefaultHttpClient(conMgr, params);
    }
    return customerHttpClient;
  }
Example #9
0
  static {
    httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();

    // set the time out of the connection/ socket. and the cache size
    HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
    HttpConnectionParams.setSoTimeout(params, 30 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // set the connection manager factory
    params.setParameter(
        ClientPNames.CONNECTION_MANAGER_FACTORY,
        new ClientConnectionManagerFactory() {
          public ClientConnectionManager newInstance(
              HttpParams params, SchemeRegistry schemeRegistry) {
            return new ThreadSafeClientConnManager(params, schemeRegistry);
          }
        });

    // set the redirect, default is true
    HttpClientParams.setRedirecting(params, true);

    // set the client verion
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    // set user-agent
    HttpProtocolParams.setUserAgent(params, "eoeWIKI_Android/0.9");
    // set the charset
    HttpProtocolParams.setHttpElementCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    // set not activate Expect:100-Continue
    HttpProtocolParams.setUseExpectContinue(params, false);

    // set the version of the cookie
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);
  }
Example #10
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();
   }
 }
  /** LDR4JのHTTPクライアントを構築します。 */
  protected AbstractLDRHttpClient() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, LDR4J.TITLE + "/" + LDR4J.VERSION);

    httpClient = new DefaultHttpClient(params);
  }
Example #12
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>();
  }
 @Override
 protected void setUserAgent(String userAgent) {
   super.setUserAgent(userAgent);
   if (mHttpClient != null) {
     HttpParams params = mHttpClient.getParams();
     HttpProtocolParams.setUserAgent(params, config.getUserAgent());
     mHttpClient.setParams(params);
     HttpLog.i(TAG, "lite-http set User-Agent: " + userAgent);
   }
 }
Example #14
0
 static {
   HttpParams params = new BasicHttpParams();
   HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setContentCharset(params, "UTF-8");
   HttpProtocolParams.setUserAgent(params, WeaveConstants.USER_AGENT);
   HttpProtocolParams.setUseExpectContinue(params, false);
   //    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
   params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
   params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
   sm_httpParams = params;
 }
  public BaseIndexesFetcher() {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000);
    HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);
    HttpProtocolParams.setUserAgent(params, Constants.USER_AGENT);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    this.client = new DefaultHttpClient(cm, params);
  }
  @Override
  protected void onPreExecute() {
    mHttpClient = new DefaultHttpClient();

    HttpParams httpParams = mHttpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, Huaban.TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, Huaban.TIMEOUT);
    HttpProtocolParams.setUserAgent(httpParams, Huaban.USER_AGENT);

    mListener.onStart();
  }
Example #17
0
  @SuppressWarnings("deprecation")
  @Test
  public final void givenDeprecatedApi_whenClientUsesCustomUserAgent_thenCorrect()
      throws ClientProtocolException, IOException {
    final DefaultHttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 Firefox/26.0");
    HttpProtocolParams.setUserAgent(client.getParams(), "Mozilla/5.0 Firefox/26.0");

    final HttpGet request = new HttpGet(SAMPLE_URL);
    response = client.execute(request);
  }
Example #18
0
  private static HttpParams createDefaultHttpParams(int timeout) {
    HttpParams params = new BasicHttpParams();
    /* default HTTP parameters */
    DefaultHttpClient.setDefaultHttpParams(params);
    /* connection/socket timeouts */
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setConnectionTimeout(params, timeout);

    /* user agent */
    HttpProtocolParams.setUserAgent(params, "cosbench/2.0");
    return params;
  }
Example #19
0
  private HttpResponse execute(HttpUriRequest request) throws IOException {
    if (httpParams == null) {
      httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
      HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
      HttpProtocolParams.setUserAgent(httpParams, USER_AGENT);
    }

    createContext();

    HttpClient client = new DefaultHttpClient(httpParams);
    return client.execute(request, context);
  }
Example #20
0
  public static synchronized HttpClient getInstance(Context context) {
    if (null == customerHttpClient) {

      HttpParams params = new BasicHttpParams();

      // 设置一些基本参数
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params, CHARSET);
      HttpProtocolParams.setUseExpectContinue(params, true);
      HttpProtocolParams.setUserAgent(
          params, System.getProperties().getProperty("http.agent") + " Mozilla/5.0 Firefox/26.0");

      // 超时设置
      /* 从连接池中取连接的超时时间 */
      ConnManagerParams.setTimeout(params, 10 * 1000);

      /* 连接超时 */
      HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);

      /* 请求超时 */
      HttpConnectionParams.setSoTimeout(params, 10 * 1000);

      // 支持http和https两种模式
      SchemeRegistry schReg = new SchemeRegistry();
      schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      schReg.register(new Scheme("https", getSSLSocketFactory(), 443));

      // 使用线程安全的连接管理来创建HttpClient
      ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

      customerHttpClient = new DefaultHttpClient(conMgr, params);
      customerHttpClient.setHttpRequestRetryHandler(requestRetryHandler);
      ConnectivityManager manager =
          (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

      NetworkInfo networkinfo = manager.getActiveNetworkInfo();
      String net = networkinfo != null ? networkinfo.getExtraInfo() : null;

      // wifi的值为空
      if (!TextUtils.isEmpty(net)) {
        String proxyHost = getDefaultHost();

        if (!TextUtils.isEmpty(proxyHost)) {
          HttpHost proxy = new HttpHost(proxyHost, getDefaultPort(), "http");

          customerHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
      }
    }
    return customerHttpClient;
  }
  public byte[] post(String postBody, String contentType) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpPost httpPost = new HttpPost(uri);

    StringEntity stringEntity = new StringEntity(postBody);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    httpPost.setEntity(stringEntity);

    HttpParams params = httpPost.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, DEFAULT_USER_AGENT);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpPost);

      if (response.getStatusLine().getStatusCode() < 200
          || response.getStatusLine().getStatusCode() >= 300)
        throw new IOException(
            "bad status code, upload file " + response.getStatusLine().getStatusCode());

      if (response.getEntity() != null) {
        response.getEntity().writeTo(baos);
      }

      body = baos.toByteArray();

      if (body == null || body.length == 0) {
        throw new IOException("invalid response");
      }

      return body;
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new IOException("Http error: " + e.getMessage());
    } finally {
      try {
        baos.close();
      } catch (IOException e) {
      }
    }
  }
Example #22
0
  /**
   * Creates a standard Apache HttpClient that is thread safe, supports different SSL auth methods
   * and basic authentication
   *
   * @param sslTrustAll Whether to trust all SSL certificates
   * @param sslTrustKey A specific SSL key to accept exclusively
   * @param timeout The connection timeout for all requests
   * @param authAddress The authentication domain address
   * @param authPort The authentication domain port number
   * @return An HttpClient that should be stored locally and reused for every new request
   * @throws DaemonException Thrown when information (such as username/password) is missing
   */
  public static DefaultHttpClient createStandardHttpClient(
      boolean userBasicAuth,
      String username,
      String password,
      boolean sslTrustAll,
      String sslTrustKey,
      int timeout,
      String authAddress,
      int authPort)
      throws DaemonException {

    // Register http and https sockets
    SchemeRegistry registry = new SchemeRegistry();
    SocketFactory httpsSocketFactory;
    if (sslTrustKey != null && sslTrustKey.length() != 0) {
      httpsSocketFactory = new TlsSniSocketFactory(sslTrustKey);
    } else if (sslTrustAll) {
      httpsSocketFactory = new TlsSniSocketFactory(true);
    } else {
      httpsSocketFactory = new TlsSniSocketFactory();
    }
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    registry.register(new Scheme("https", httpsSocketFactory, 443));

    // Standard parameters
    HttpParams httpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams, timeout);
    HttpConnectionParams.setSoTimeout(httpparams, timeout);
    if (userAgent != null) {
      HttpProtocolParams.setUserAgent(httpparams, userAgent);
    }

    DefaultHttpClient httpclient =
        new DefaultHttpClient(new ThreadSafeClientConnManager(httpparams, registry), httpparams);

    // Authentication credentials
    if (userBasicAuth) {
      if (username == null || password == null) {
        throw new DaemonException(
            ExceptionType.AuthenticationFailure,
            "No username or password was provided while we had authentication enabled");
      }
      httpclient
          .getCredentialsProvider()
          .setCredentials(
              new AuthScope(authAddress, authPort, AuthScope.ANY_REALM),
              new UsernamePasswordCredentials(username, password));
    }

    return httpclient;
  }
Example #23
0
  /** Fetches a file from the URL given and returns an input stream to it. */
  private static InputStream fetchFile(String url)
      throws IOException, ClientProtocolException, FileNotFoundException {

    HttpParams httpClientParams = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(httpClientParams, VersionInfoUtils.getUserAgent());
    HttpClient httpclient = new DefaultHttpClient(httpClientParams);
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
      return entity.getContent();
    }
    return null;
  }
  public void save(File file, HttpFetcherListener listener) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("Connection", "close");

    HttpParams params = httpGet.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, userAgent);

    FileOutputStream out = null;

    int statusCode = -1;
    Map<String, String> headers = null;

    try {

      out = new FileOutputStream(file);

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpGet);

      statusCode = response.getStatusLine().getStatusCode();
      headers = mapHeaders(response.headerIterator());

      if (statusCode < 200 || statusCode >= 300) {
        throw new IOException("bad status code, downloading file " + statusCode);
      }

      if (response.getEntity() != null) {
        writeEntity(response.getEntity(), out, listener);
      }

      if (listener != null) {
        listener.onSuccess(new byte[0]);
      }

    } catch (Throwable e) {
      if (listener != null) {
        listener.onError(e, statusCode, headers);
      }
      Log.e(TAG, "Error downloading from: " + uri + ", e: " + e.getMessage());
    } finally {
      IOUtils.closeQuietly(out);
    }
  }
 static {
   // Prepare HTTP parameters.
   HttpParams params = new BasicHttpParams();
   HttpConnectionParams.setStaleCheckingEnabled(params, false);
   HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
   HttpConnectionParams.setSoTimeout(params, CONNECTION_TIMEOUT);
   HttpClientParams.setRedirecting(params, true);
   HttpProtocolParams.setUserAgent(params, USER_AGENT);
   HTTP_PARAMS = params;
   // Register HTTP protocol.
   SchemeRegistry schemeRegistry = new SchemeRegistry();
   schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
   // Create the connection manager.
   HTTP_CONNECTION_MANAGER = new ThreadSafeClientConnManager(params, schemeRegistry);
 }
Example #26
0
 private static void setupHttpClient() {
   BasicHttpParams httpParams = new BasicHttpParams();
   ConnManagerParams.setTimeout(httpParams, CONNECTION_TIMEOUT);
   ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(MAX_CONNECTIONS));
   ConnManagerParams.setMaxTotalConnections(httpParams, MAX_CONNECTIONS);
   HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setUserAgent(httpParams, HTTP_USER_AGENT);
   SchemeRegistry schemeRegistry = new SchemeRegistry();
   schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
   // schemeRegistry.register(new Scheme("https", new
   // EasySSLProtocolSocketFactory(), 443));
   ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
   HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
   httpClient = new DefaultHttpClient(cm, httpParams);
 }
 /** initialize HttpParams , initialize settings such as total connextions,timeout ... */
 private BasicHttpParams createHttpParams() {
   BasicHttpParams params = new BasicHttpParams();
   ConnManagerParams.setTimeout(params, config.getConnectTimeout());
   ConnManagerParams.setMaxConnectionsPerRoute(
       params, new ConnPerRouteBean(DEFAULT_MAX_CONN_PER_ROUT));
   ConnManagerParams.setMaxTotalConnections(params, DEFAULT_MAX_CONN_TOTAL);
   HttpConnectionParams.setTcpNoDelay(params, TCP_NO_DELAY);
   HttpConnectionParams.setConnectionTimeout(params, config.getConnectTimeout());
   HttpConnectionParams.setSoTimeout(params, config.getSocketTimeout());
   HttpConnectionParams.setSocketBufferSize(params, config.getSocketBufferSize());
   HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setUserAgent(params, config.getUserAgent());
   // settingOthers(params);
   return params;
 }
  @Override
  protected HttpParams createHttpParams() {
    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // determine the release version from packaged version info
    final VersionInfo vi =
        VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader());
    final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
    HttpProtocolParams.setUserAgent(params, "Apache-HttpClient/" + release + " (java 1.5)");

    return params;
  }
 @Override
 public void initConfig(HttpConfig config) {
   if (config == null) {
     config = new HttpConfig(null);
   }
   super.initConfig(config);
   retryHandler =
       new HttpRetryHandler(config.getRetrySleepMillis(), config.isRequestSentRetryEnabled());
   if (mHttpClient != null) {
     HttpParams params = mHttpClient.getParams();
     HttpConnectionParams.setConnectionTimeout(params, config.getConnectTimeout());
     HttpConnectionParams.setSoTimeout(params, config.getSocketTimeout());
     HttpConnectionParams.setSocketBufferSize(params, config.getSocketBufferSize());
     HttpProtocolParams.setUserAgent(params, config.getUserAgent());
     mHttpClient.setParams(params);
   }
 }
Example #30
0
  /**
   * Fetches a file from the URI given and returns an input stream to it.
   *
   * @param uri the uri of the file to fetch
   * @param config optional configuration overrides
   * @return an InputStream containing the retrieved data
   * @throws IOException on error
   */
  public static InputStream fetchFile(final URI uri, final ClientConfiguration config)
      throws IOException {

    HttpParams httpClientParams = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(httpClientParams, getUserAgent(config));

    HttpConnectionParams.setConnectionTimeout(httpClientParams, getConnectionTimeout(config));
    HttpConnectionParams.setSoTimeout(httpClientParams, getSocketTimeout(config));

    DefaultHttpClient httpclient = new DefaultHttpClient(httpClientParams);

    if (config != null) {
      String proxyHost = config.getProxyHost();
      int proxyPort = config.getProxyPort();

      if (proxyHost != null && proxyPort > 0) {

        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        if (config.getProxyUsername() != null && config.getProxyPassword() != null) {

          httpclient
              .getCredentialsProvider()
              .setCredentials(
                  new AuthScope(proxyHost, proxyPort),
                  new NTCredentials(
                      config.getProxyUsername(),
                      config.getProxyPassword(),
                      config.getProxyWorkstation(),
                      config.getProxyDomain()));
        }
      }
    }

    HttpResponse response = httpclient.execute(new HttpGet(uri));

    if (response.getStatusLine().getStatusCode() != 200) {
      throw new IOException("Error fetching file from " + uri + ": " + response);
    }

    return new HttpClientWrappingInputStream(httpclient, response.getEntity().getContent());
  }