Java Code Examples for org.apache.http.params.BasicHttpParams

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project airlift, under directory /http-client/src/main/java/io/airlift/http/client/.

Source file: ApacheHttpClient.java

  18 
vote

public ApacheHttpClient(HttpClientConfig config,Set<HttpRequestFilter> requestFilters){
  Preconditions.checkNotNull(config,"config is null");
  Preconditions.checkNotNull(requestFilters,"requestFilters is null");
  PoolingClientConnectionManager connectionManager=new PoolingClientConnectionManager();
  connectionManager.setMaxTotal(config.getMaxConnections());
  connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerServer());
  BasicHttpParams httpParams=new BasicHttpParams();
  httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT,(int)config.getReadTimeout().toMillis());
  httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,(int)config.getConnectTimeout().toMillis());
  httpParams.setParameter(CoreConnectionPNames.SO_LINGER,0);
  this.httpClient=new DefaultHttpClient(connectionManager,httpParams);
  this.requestFilters=ImmutableList.copyOf(requestFilters);
}
 

Example 2

From project Amantech, under directory /Android/CloudAppStudioAndroid/src/com/cloudappstudio/utility/.

Source file: CloudOAuth.java

  18 
vote

public String getContent(String apiUrl) throws IllegalStateException, IOException {
  DefaultHttpClient httpClient=new DefaultHttpClient();
  BasicHttpParams params=new BasicHttpParams();
  HttpClientParams.setRedirecting(params,false);
  httpClient.setParams(params);
  HttpGet httpget=new HttpGet(apiUrl + "?userInfoOAuth=" + id.getToken());
  HttpResponse response=httpClient.execute(httpget);
  Log.d("debug","" + response.getStatusLine().getStatusCode());
  Log.d("debug","" + response.getStatusLine());
  return this.readTextFromHttpResponse(response);
}
 

Example 3

From project android-rackspacecloud, under directory /extensions/httpnio/src/main/java/org/jclouds/http/httpnio/config/.

Source file: NioTransformingHttpCommandExecutorServiceModule.java

  18 
vote

@Singleton @Provides HttpParams newBasicHttpParams(HttpUtils utils){
  BasicHttpParams params=new BasicHttpParams();
  params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,8 * 1024).setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,true).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,true).setParameter(CoreProtocolPNames.ORIGIN_SERVER,"jclouds/1.0");
  if (utils.getConnectionTimeout() > 0) {
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,utils.getConnectionTimeout());
  }
  if (utils.getSocketOpenTimeout() > 0) {
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,utils.getSocketOpenTimeout());
  }
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  return params;
}
 

Example 4

From project dreamDroid, under directory /src/net/reichholf/dreamdroid/helpers/.

Source file: SimpleHttpClient.java

  18 
vote

/** 
 * @param sp SharedPreferences of the Base-Context
 */
public SimpleHttpClient(){
  BasicHttpParams params=new BasicHttpParams();
  params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);
  mDhc=new DefaultHttpClient(getEasySSLClientConnectionManager(),params);
  mContext=new BasicHttpContext();
  applyConfig();
}
 

Example 5

From project droid-fu, under directory /src/test/java/com/github/droidfu/http/.

Source file: BetterHttpTestBase.java

  18 
vote

@SuppressWarnings("unchecked") @Before public void setupHttpClient() throws Exception {
  when(mockResponse.getResponseBody()).thenReturn(new ByteArrayInputStream(responseBody.getBytes()));
  when(mockResponse.getResponseBodyAsBytes()).thenReturn(responseBody.getBytes());
  when(mockResponse.getResponseBodyAsString()).thenReturn(responseBody);
  when(mockResponse.getStatusCode()).thenReturn(200);
  when(httpClientMock.execute(any(HttpUriRequest.class),any(ResponseHandler.class),any(HttpContext.class))).thenReturn(mockResponse);
  BasicHttpParams params=new BasicHttpParams();
  HttpConnectionParams.setSoTimeout(params,BetterHttp.DEFAULT_SOCKET_TIMEOUT);
  when(httpClientMock.getParams()).thenReturn(params);
  BetterHttp.setHttpClient(httpClientMock);
}
 

Example 6

From project javaee-tutorial, under directory /jaxrs/android/src/org/jboss/ee/tutorial/jaxrs/android/data/.

Source file: LibraryHttpClient.java

  18 
vote

public LibraryHttpClient(Context context){
  this.context=context;
  BasicHttpParams params=new BasicHttpParams();
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(params,HTTP.DEFAULT_CONTENT_CHARSET);
  HttpProtocolParams.setUseExpectContinue(params,false);
  httpClient=new DefaultHttpClient(params);
}
 

Example 7

From project platform_3, under directory /http-client/src/main/java/com/proofpoint/http/client/.

Source file: ApacheHttpClient.java

  18 
vote

public ApacheHttpClient(HttpClientConfig config,Set<HttpRequestFilter> requestFilters){
  Preconditions.checkNotNull(config,"config is null");
  Preconditions.checkNotNull(requestFilters,"requestFilters is null");
  PoolingClientConnectionManager connectionManager=new PoolingClientConnectionManager();
  connectionManager.setMaxTotal(config.getMaxConnections());
  connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerServer());
  BasicHttpParams httpParams=new BasicHttpParams();
  httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT,(int)config.getReadTimeout().toMillis());
  httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,(int)config.getConnectTimeout().toMillis());
  httpParams.setParameter(CoreConnectionPNames.SO_LINGER,0);
  this.httpClient=new DefaultHttpClient(connectionManager,httpParams);
  this.requestFilters=ImmutableList.copyOf(requestFilters);
}
 

Example 8

From project Airports, under directory /src/com/nadmm/airports/utils/.

Source file: NetworkUtils.java

  17 
vote

public static HttpClient getHttpClient(){
  SchemeRegistry registry=new SchemeRegistry();
  registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  HttpParams params=new BasicHttpParams();
  ClientConnectionManager cm=new ThreadSafeClientConnManager(params,registry);
  HttpClient client=new DefaultHttpClient(cm,params);
  return client;
}
 

Example 9

From project android-api_1, under directory /android-lib/src/com/catchnotes/api/.

Source file: CatchAPI.java

  17 
vote

private HttpClient getHttpClientNoToken(){
  if (httpClientNoToken == null) {
    HttpParams params=new BasicHttpParams();
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params,userAgent);
    HttpProtocolParams.setContentCharset(params,"UTF-8");
    httpClientNoToken=new DefaultHttpClient(params);
  }
  return httpClientNoToken;
}
 

Example 10

From project android-client, under directory /xwiki-android-rest/src/org/xwiki/android/rest/.

Source file: HttpConnector.java

  17 
vote

/** 
 * initialize the general property fields
 */
private void initialize(){
  client=new DefaultHttpClient();
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,10000);
  HttpConnectionParams.setSoTimeout(params,20000);
  client.setParams(params);
}
 

Example 11

From project android_packages_apps_Exchange, under directory /src/com/android/exchange/.

Source file: EasSyncService.java

  17 
vote

private HttpClient getHttpClient(int timeout){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,CONNECTION_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,timeout);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpClient client=new DefaultHttpClient(getClientConnectionManager(),params);
  return client;
}
 

Example 12

From project apps-for-android, under directory /Photostream/src/com/google/android/photostream/.

Source file: Flickr.java

  17 
vote

private void Flickr(){
  final HttpParams params=new BasicHttpParams();
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(params,"UTF-8");
  final SchemeRegistry registry=new SchemeRegistry();
  registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  final ThreadSafeClientConnManager manager=new ThreadSafeClientConnManager(params,registry);
  mClient=new DefaultHttpClient(manager,params);
}
 

Example 13

From project bbb-java, under directory /src/main/java/org/mconf/web/.

Source file: Authentication.java

  17 
vote

@SuppressWarnings("deprecation") public Authentication(String server,String username,String password) throws HttpException, IOException {
  this.server=server;
  SchemeRegistry registry=new SchemeRegistry();
  registry.register(new Scheme("http",new PlainSocketFactory(),80));
  registry.register(new Scheme("https",new FakeSocketFactory(),443));
  HttpParams params=new BasicHttpParams();
  params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,false);
  client=new DefaultHttpClient(new ThreadSafeClientConnManager(params,registry),params);
  authenticated=authenticate(username,password);
}
 

Example 14

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/goodreads/.

Source file: GoodreadsManager.java

  17 
vote

/** 
 * Create an HttpClient with specifically set buffer sizes to deal with potentially exorbitant settings on some HTC handsets.
 * @return
 */
private HttpClient newHttpClient(){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,30000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpConnectionParams.setLinger(params,0);
  HttpConnectionParams.setTcpNoDelay(params,false);
  HttpClient httpClient=new DefaultHttpClient(params);
  return httpClient;
}
 

Example 15

From project build-info, under directory /build-info-client/src/main/java/org/jfrog/build/client/.

Source file: PreemptiveHttpClient.java

  17 
vote

private DefaultHttpClient createHttpClient(String userName,String password,int timeout){
  BasicHttpParams params=new BasicHttpParams();
  int timeoutMilliSeconds=timeout * 1000;
  HttpConnectionParams.setConnectionTimeout(params,timeoutMilliSeconds);
  HttpConnectionParams.setSoTimeout(params,timeoutMilliSeconds);
  DefaultHttpClient client=new DefaultHttpClient(params);
  if (userName != null && !"".equals(userName)) {
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST,AuthScope.ANY_PORT),new UsernamePasswordCredentials(userName,password));
    localContext=new BasicHttpContext();
    BasicScheme basicAuth=new BasicScheme();
    localContext.setAttribute("preemptive-auth",basicAuth);
    client.addRequestInterceptor(new PreemptiveAuth(),0);
  }
  String userAgent="ArtifactoryBuildClient/" + CLIENT_VERSION;
  HttpProtocolParams.setUserAgent(client.getParams(),userAgent);
  return client;
}
 

Example 16

From project BusFollower, under directory /src/net/argilo/busfollower/ocdata/.

Source file: OCTranspoDataFetcher.java

  17 
vote

private HttpParams getHttpParams(){
  HttpParams httpParams=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_CONNECTION);
  HttpConnectionParams.setSoTimeout(httpParams,TIMEOUT_SOCKET);
  return httpParams;
}
 

Example 17

From project capedwarf-blue, under directory /urlfetch/src/main/java/org/jboss/capedwarf/urlfetch/.

Source file: JBossURLFetchService.java

  17 
vote

protected HttpClient getClient(){
  if (client == null) {
    SchemeRegistry schemeRegistry=new SchemeRegistry();
    schemeRegistry.register(new Scheme("http",80,PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https",443,SSLSocketFactory.getSocketFactory()));
    HttpParams params=new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params,30 * 1000);
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params,"UTF-8");
    ClientConnectionManager ccm=new ThreadSafeClientConnManager(schemeRegistry);
    client=new DefaultHttpClient(ccm,params);
  }
  return client;
}
 

Example 18

From project crest, under directory /core/src/test/java/org/codegist/crest/io/http/.

Source file: HttpClientFactoryTest.java

  17 
vote

@Test public void createWithMoreThanOneShouldCreateDefaultHttpClientWithConnectionManagerSetup() throws Exception {
  DefaultHttpClient expected=mock(DefaultHttpClient.class);
  ProxySelectorRoutePlanner planner=mock(ProxySelectorRoutePlanner.class);
  ClientConnectionManager clientConnectionManager=mock(ClientConnectionManager.class);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  ProxySelector proxySelector=mock(ProxySelector.class);
  BasicHttpParams httpParams=mock(BasicHttpParams.class);
  ConnPerRouteBean routeBean=mock(ConnPerRouteBean.class);
  PlainSocketFactory plainSocketFactory=mock(PlainSocketFactory.class);
  SSLSocketFactory sslSocketFactory=mock(SSLSocketFactory.class);
  Scheme plainScheme=new Scheme("http",plainSocketFactory,80);
  Scheme sslScheme=new Scheme("https",sslSocketFactory,443);
  ThreadSafeClientConnManager threadSafeClientConnManager=mock(ThreadSafeClientConnManager.class);
  when(expected.getConnectionManager()).thenReturn(clientConnectionManager);
  when(clientConnectionManager.getSchemeRegistry()).thenReturn(schemeRegistry);
  mockStatic(ProxySelector.class);
  when(ProxySelector.getDefault()).thenReturn(proxySelector);
  mockStatic(PlainSocketFactory.class);
  when(PlainSocketFactory.getSocketFactory()).thenReturn(plainSocketFactory);
  mockStatic(SSLSocketFactory.class);
  when(SSLSocketFactory.getSocketFactory()).thenReturn(sslSocketFactory);
  whenNew(SchemeRegistry.class).withNoArguments().thenReturn(schemeRegistry);
  whenNew(Scheme.class).withArguments("http",plainSocketFactory,80).thenReturn(plainScheme);
  whenNew(Scheme.class).withArguments("https",sslSocketFactory,443).thenReturn(sslScheme);
  whenNew(ThreadSafeClientConnManager.class).withArguments(httpParams,schemeRegistry).thenReturn(threadSafeClientConnManager);
  whenNew(ConnPerRouteBean.class).withArguments(2).thenReturn(routeBean);
  whenNew(BasicHttpParams.class).withNoArguments().thenReturn(httpParams);
  whenNew(DefaultHttpClient.class).withArguments(threadSafeClientConnManager,httpParams).thenReturn(expected);
  whenNew(ProxySelectorRoutePlanner.class).withArguments(schemeRegistry,proxySelector).thenReturn(planner);
  when(crestConfig.getConcurrencyLevel()).thenReturn(2);
  HttpClient actual=HttpClientFactory.create(crestConfig,getClass());
  assertSame(expected,actual);
  verify(expected).setRoutePlanner(planner);
  verify(httpParams).setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
  verify(httpParams).setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE,routeBean);
  verify(httpParams).setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS,2);
  assertSame(plainScheme,schemeRegistry.getScheme("http"));
  assertSame(sslScheme,schemeRegistry.getScheme("https"));
}
 

Example 19

From project DeliciousDroid, under directory /src/com/deliciousdroid/client/.

Source file: HttpClientFactory.java

  17 
vote

public static HttpClient getThreadSafeClient(){
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,100);
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpConnectionParams.setConnectionTimeout(params,REGISTRATION_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,REGISTRATION_TIMEOUT);
  ConnManagerParams.setTimeout(params,REGISTRATION_TIMEOUT);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager mgr=new ThreadSafeClientConnManager(params,schemeRegistry);
  HttpClient client=new DefaultHttpClient(mgr,params);
  return client;
}
 

Example 20

From project eve-api, under directory /cdi/src/main/java/org/onsteroids/eve/api/connector/http/.

Source file: PooledHttpApiConnection.java

  17 
vote

/** 
 * Initializses and configures the http client connection pool.
 */
private void initializeHttpClient(){
  LOG.debug("Configuring the HttpClientPool with a maximum of {} connections",maxConnections);
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,maxConnections);
  ConnPerRouteBean connPerRoute=new ConnPerRouteBean(maxConnections);
  HttpHost serverHost=new HttpHost(serverUri.getHost(),serverUri.getPort());
  connPerRoute.setMaxForRoute(new HttpRoute(serverHost),maxConnections);
  ConnManagerParams.setMaxConnectionsPerRoute(params,connPerRoute);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager cm=new ThreadSafeClientConnManager(params,schemeRegistry);
  httpClient=new DefaultHttpClient(cm,params);
}
 

Example 21

From project exo.social.client, under directory /src/main/java/org/exoplatform/social/client/core/net/.

Source file: SocialHttpClientImpl.java

  17 
vote

/** 
 * Create a new HttpClient with reasonable defaults.
 * @return SocialHttpClient for you to use for all your requests.
 */
public static SocialHttpClient newInstance(){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  HttpConnectionParams.setConnectionTimeout(params,SOCKET_OPERATION_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,SOCKET_OPERATION_TIMEOUT);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpClientParams.setRedirecting(params,false);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  ClientConnectionManager manager=new ThreadSafeClientConnManager(params,schemeRegistry);
  return new SocialHttpClientImpl(manager,params);
}
 

Example 22

From project fanfoudroid, under directory /src/com/ch_linghu/fanfoudroid/http/.

Source file: HttpClient.java

  17 
vote

/** 
 * Setup DefaultHttpClient Use ThreadSafeClientConnManager.
 */
private void prepareHttpClient(){
  if (DEBUG) {
    enableDebug();
  }
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,10);
  HttpProtocolParams.setVersion(params,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(params,schemeRegistry);
  mClient=new DefaultHttpClient(cm,params);
  mClient.addResponseInterceptor(gzipResponseIntercepter);
}
 

Example 23

From project FlipDroid, under directory /app/src/com/goal98/flipdroid2/client/.

Source file: HttpClientFactory.java

  17 
vote

public static synchronized HttpClient getHttpClient(){
  if (client == null) {
    HttpParams params=new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params,MAX_TOTAL_CONNECTIONS);
    ConnPerRouteBean connPerRoute=new ConnPerRouteBean(MAX_PER_ROUTE);
    ConnManagerParams.setMaxConnectionsPerRoute(params,connPerRoute);
    SchemeRegistry registry=new SchemeRegistry();
    registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
    ClientConnectionManager cm=new ThreadSafeClientConnManager(params,registry);
    client=new DefaultHttpClient(cm,params);
  }
  System.out.println("return cached client");
  return client;
}
 

Example 24

From project Game_3, under directory /android/src/playn/android/.

Source file: AndroidHttpClient.java

  17 
vote

/** 
 * Create a new HttpClient with reasonable defaults (which you can update).
 * @param userAgent to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  HttpConnectionParams.setConnectionTimeout(params,20 * 1000);
  HttpConnectionParams.setSoTimeout(params,20 * 1000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpClientParams.setRedirecting(params,false);
  HttpProtocolParams.setUserAgent(params,userAgent);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager manager=new ThreadSafeClientConnManager(params,schemeRegistry);
  return new AndroidHttpClient(manager,params);
}
 

Example 25

From project generic-store-for-android, under directory /src/com/wareninja/opensource/common/.

Source file: WebService.java

  17 
vote

public WebService(String serviceName){
  HttpParams myParams=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(myParams,20000);
  HttpConnectionParams.setSoTimeout(myParams,20000);
  httpClient=new DefaultHttpClient(myParams);
  localContext=new BasicHttpContext();
  webServiceUrl=serviceName;
}
 

Example 26

From project hsDroid, under directory /src/de/nware/app/hsDroid/provider/.

Source file: HttpClientFactory.java

  17 
vote

public synchronized static DefaultHttpClient getHttpClient(int connectionTimeoutMillis){
  if (httpClient == null) {
    httpClient=new DefaultHttpClient();
    ClientConnectionManager connectionManager=httpClient.getConnectionManager();
    HttpParams httpParams=new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,connectionTimeoutMillis);
    httpClient=new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams,connectionManager.getSchemeRegistry()),httpParams);
  }
  return httpClient;
}
 

Example 27

From project httpbuilder, under directory /src/main/java/groovyx/net/http/.

Source file: AsyncHTTPBuilder.java

  17 
vote

/** 
 * Initializes threading parameters for the HTTPClient's  {@link ThreadSafeClientConnManager}, and this class' ThreadPoolExecutor. 
 */
protected void initThreadPools(final int poolSize,final ExecutorService threadPool){
  if (poolSize < 1)   throw new IllegalArgumentException("poolSize may not be < 1");
  HttpParams params=client != null ? client.getParams() : new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,poolSize);
  ConnManagerParams.setMaxConnectionsPerRoute(params,new ConnPerRouteBean(poolSize));
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager cm=new ThreadSafeClientConnManager(params,schemeRegistry);
  super.client=new DefaultHttpClient(cm,params);
  this.threadPool=threadPool != null ? threadPool : new ThreadPoolExecutor(poolSize,poolSize,120,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
}
 

Example 28

From project httpClient, under directory /httpclient/src/test/java/org/apache/http/conn/params/.

Source file: TestRouteParams.java

  17 
vote

@Test public void testSetGet(){
  HttpParams params=new BasicHttpParams();
  Assert.assertNull("phantom proxy",ConnRouteParams.getDefaultProxy(params));
  Assert.assertNull("phantom route",ConnRouteParams.getForcedRoute(params));
  Assert.assertNull("phantom address",ConnRouteParams.getLocalAddress(params));
  ConnRouteParams.setDefaultProxy(params,TARGET1);
  Assert.assertSame("wrong proxy",TARGET1,ConnRouteParams.getDefaultProxy(params));
  ConnRouteParams.setForcedRoute(params,ROUTE1);
  Assert.assertSame("wrong route",ROUTE1,ConnRouteParams.getForcedRoute(params));
  ConnRouteParams.setLocalAddress(params,LOCAL1);
  Assert.assertSame("wrong address",LOCAL1,ConnRouteParams.getLocalAddress(params));
}
 

Example 29

From project httpcore, under directory /httpcore/src/main/java/org/apache/http/message/.

Source file: AbstractHttpMessage.java

  17 
vote

public HttpParams getParams(){
  if (this.params == null) {
    this.params=new BasicHttpParams();
  }
  return this.params;
}
 

Example 30

From project huiswerk, under directory /print/zxing-1.6/android/src/com/google/zxing/client/android/.

Source file: AndroidHttpClient.java

  17 
vote

/** 
 * Create a new HttpClient with reasonable defaults (which you can update).
 * @param userAgent to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  HttpConnectionParams.setConnectionTimeout(params,20 * 1000);
  HttpConnectionParams.setSoTimeout(params,20 * 1000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpClientParams.setRedirecting(params,false);
  HttpProtocolParams.setUserAgent(params,userAgent);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager manager=new ThreadSafeClientConnManager(params,schemeRegistry);
  return new AndroidHttpClient(manager,params);
}
 

Example 31

From project ignition, under directory /ignition-support/ignition-support-lib/src/main/java/com/github/ignition/support/http/.

Source file: IgnitedHttp.java

  17 
vote

protected void setupHttpClient(){
  BasicHttpParams httpParams=new BasicHttpParams();
  ConnManagerParams.setTimeout(httpParams,DEFAULT_WAIT_FOR_CONNECTION_TIMEOUT);
  ConnManagerParams.setMaxConnectionsPerRoute(httpParams,new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
  ConnManagerParams.setMaxTotalConnections(httpParams,DEFAULT_MAX_CONNECTIONS);
  HttpConnectionParams.setSoTimeout(httpParams,DEFAULT_SOCKET_TIMEOUT);
  HttpConnectionParams.setTcpNoDelay(httpParams,true);
  HttpProtocolParams.setVersion(httpParams,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setUserAgent(httpParams,DEFAULT_HTTP_USER_AGENT);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  if (IgnitedDiagnostics.ANDROID_API_LEVEL >= 7) {
    schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  }
 else {
    schemeRegistry.register(new Scheme("https",new EasySSLSocketFactory(),443));
  }
  ThreadSafeClientConnManager cm=new ThreadSafeClientConnManager(httpParams,schemeRegistry);
  httpClient=new DefaultHttpClient(cm,httpParams);
}
 

Example 32

From project jena-fuseki, under directory /src/main/java/org/apache/jena/fuseki/http/.

Source file: DatasetGraphAccessorHTTP.java

  17 
vote

static private HttpParams createHttpParams(){
  HttpParams httpParams$=new BasicHttpParams();
  HttpProtocolParams.setVersion(httpParams$,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(httpParams$,HTTP.DEFAULT_CONTENT_CHARSET);
  HttpProtocolParams.setUseExpectContinue(httpParams$,true);
  HttpConnectionParams.setTcpNoDelay(httpParams$,true);
  HttpConnectionParams.setSocketBufferSize(httpParams$,32 * 1024);
  HttpProtocolParams.setUserAgent(httpParams$,Fuseki.NAME + "/" + Fuseki.VERSION);
  return httpParams$;
}
 

Example 33

From project jetty-project, under directory /jetty-reverse-http/reverse-http-client/src/test/java/org/mortbay/jetty/rhttp/client/.

Source file: ApacheClientTest.java

  17 
vote

protected RHTTPClient createClient(int port,String targetId) throws Exception {
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),port));
  connectionManager=new ThreadSafeClientConnManager(new BasicHttpParams(),schemeRegistry);
  HttpParams httpParams=new BasicHttpParams();
  httpParams.setParameter("http.default-host",new HttpHost("localhost",port));
  DefaultHttpClient httpClient=new DefaultHttpClient(connectionManager,httpParams);
  httpClient.setHttpRequestRetryHandler(new NoRetryHandler());
  return new ApacheClient(httpClient,"",targetId);
}
 

Example 34

From project MIT-Mobile-for-Android, under directory /src/com/google/zxing/client/android/.

Source file: AndroidHttpClient.java

  17 
vote

/** 
 * Create a new HttpClient with reasonable defaults (which you can update).
 * @param userAgent to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  HttpConnectionParams.setConnectionTimeout(params,20 * 1000);
  HttpConnectionParams.setSoTimeout(params,20 * 1000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpClientParams.setRedirecting(params,false);
  HttpProtocolParams.setUserAgent(params,userAgent);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager manager=new ThreadSafeClientConnManager(params,schemeRegistry);
  return new AndroidHttpClient(manager,params);
}
 

Example 35

From project Mobile-Tour-Guide, under directory /zxing-2.0/zxingorg/src/com/google/zxing/web/.

Source file: DecodeServlet.java

  17 
vote

@Override public void init(ServletConfig servletConfig){
  Logger logger=Logger.getLogger("com.google.zxing");
  logger.addHandler(new ServletContextLogHandler(servletConfig.getServletContext()));
  params=new BasicHttpParams();
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  registry=new SchemeRegistry();
  registry.register(new Scheme("http",80,PlainSocketFactory.getSocketFactory()));
  registry.register(new Scheme("https",443,SSLSocketFactory.getSocketFactory()));
  diskFileItemFactory=new DiskFileItemFactory();
  log.info("DecodeServlet configured");
}
 

Example 36

From project OAK, under directory /oak-library/src/main/java/oak/external/com/github/droidfu/http/.

Source file: BetterHttp.java

  17 
vote

public static void setupHttpClient(){
  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);
  HttpProtocolParams.setVersion(httpParams,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setUserAgent(httpParams,httpUserAgent);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  if (DiagnosticSupport.ANDROID_API_LEVEL >= 7) {
    schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  }
 else {
    schemeRegistry.register(new Scheme("https",new EasySSLSocketFactory(),443));
  }
  ThreadSafeClientConnManager cm=new ThreadSafeClientConnManager(httpParams,schemeRegistry);
  httpClient=new DefaultHttpClient(cm,httpParams);
}
 

Example 37

From project Orweb, under directory /src/info/guardianproject/browser/.

Source file: AnonProxy.java

  17 
vote

/** 
 * Set the port for the HTTP proxy
 * @param port
 */
public AnonProxy(){
  HttpHost proxy=new HttpHost(Browser.DEFAULT_PROXY_HOST,Integer.parseInt(Browser.DEFAULT_PROXY_PORT),"http");
  SchemeRegistry supportedSchemes=new SchemeRegistry();
  supportedSchemes.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  supportedSchemes.register(new Scheme("https",ModSSLSocketFactory.getSocketFactory(),443));
  HttpParams hparams=new BasicHttpParams();
  HttpProtocolParams.setVersion(hparams,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(hparams,"UTF-8");
  HttpProtocolParams.setUseExpectContinue(hparams,true);
  ClientConnectionManager ccm=new ThreadSafeClientConnManager(hparams,supportedSchemes);
  mClient=new DefaultHttpClient(ccm,hparams);
  mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
}
 

Example 38

From project PartyWare, under directory /android/src/com/google/zxing/client/android/.

Source file: AndroidHttpClient.java

  17 
vote

/** 
 * Create a new HttpClient with reasonable defaults (which you can update).
 * @param userAgent to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  HttpConnectionParams.setConnectionTimeout(params,20 * 1000);
  HttpConnectionParams.setSoTimeout(params,20 * 1000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpClientParams.setRedirecting(params,false);
  HttpProtocolParams.setUserAgent(params,userAgent);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager manager=new ThreadSafeClientConnManager(params,schemeRegistry);
  return new AndroidHttpClient(manager,params);
}
 

Example 39

From project PinDroid, under directory /src/com/pindroid/client/.

Source file: HttpClientFactory.java

  17 
vote

public static HttpClient getThreadSafeClient(){
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,100);
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpConnectionParams.setConnectionTimeout(params,REGISTRATION_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,REGISTRATION_TIMEOUT);
  ConnManagerParams.setTimeout(params,REGISTRATION_TIMEOUT);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager mgr=new ThreadSafeClientConnManager(params,schemeRegistry);
  HttpClient client=new DefaultHttpClient(mgr,params);
  return client;
}
 

Example 40

From project platform_external_apache-http, under directory /src/org/apache/http/impl/client/.

Source file: DefaultHttpClient.java

  17 
vote

@Override protected HttpParams createHttpParams(){
  HttpParams params=new BasicHttpParams();
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(params,HTTP.DEFAULT_CONTENT_CHARSET);
  HttpProtocolParams.setUseExpectContinue(params,false);
  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.4)");
  return params;
}
 

Example 41

From project Playlist, under directory /src/com/google/zxing/client/android/.

Source file: AndroidHttpClient.java

  17 
vote

/** 
 * Create a new HttpClient with reasonable defaults (which you can update).
 * @param userAgent to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  HttpConnectionParams.setConnectionTimeout(params,20 * 1000);
  HttpConnectionParams.setSoTimeout(params,20 * 1000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpClientParams.setRedirecting(params,false);
  HttpProtocolParams.setUserAgent(params,userAgent);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager manager=new ThreadSafeClientConnManager(params,schemeRegistry);
  return new AndroidHttpClient(manager,params);
}
 

Example 42

From project playn, under directory /android/src/playn/android/.

Source file: AndroidHttpClient.java

  17 
vote

/** 
 * Create a new HttpClient with reasonable defaults (which you can update).
 * @param userAgent to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  HttpConnectionParams.setConnectionTimeout(params,20 * 1000);
  HttpConnectionParams.setSoTimeout(params,20 * 1000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpClientParams.setRedirecting(params,false);
  HttpProtocolParams.setUserAgent(params,userAgent);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager manager=new ThreadSafeClientConnManager(params,schemeRegistry);
  return new AndroidHttpClient(manager,params);
}
 

Example 43

From project proxy-servlet, under directory /src/main/java/com/woonoz/proxy/servlet/.

Source file: ProxyServlet.java

  17 
vote

public void init(ProxyServletConfig config){
  targetServer=config.getTargetUrl();
  if (targetServer != null) {
    SchemeRegistry schemeRegistry=new SchemeRegistry();
    schemeRegistry.register(new Scheme(targetServer.getProtocol(),getPortOrDefault(targetServer.getPort()),PlainSocketFactory.getSocketFactory()));
    BasicHttpParams httpParams=new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpParams,config.getSocketTimeout());
    ThreadSafeClientConnManager cm=new ThreadSafeClientConnManager(schemeRegistry);
    cm.setDefaultMaxPerRoute(config.getMaxConnections());
    cm.setMaxTotal(config.getMaxConnections());
    client=new DefaultHttpClient(cm,httpParams);
    client.removeResponseInterceptorByClass(ResponseProcessCookies.class);
    client.removeRequestInterceptorByClass(RequestAddCookies.class);
    final String remoteUserHeader=config.getRemoteUserHeader();
    if (null != remoteUserHeader) {
      client.addRequestInterceptor(new HttpRequestInterceptor(){
        @Override public void process(        HttpRequest request,        HttpContext context) throws HttpException, IOException {
          request.removeHeaders(remoteUserHeader);
          HttpRequestHandler handler;
          if (context != null && (handler=(HttpRequestHandler)context.getAttribute(HttpRequestHandler.class.getName())) != null) {
            String remoteUser=handler.getRequest().getRemoteUser();
            if (remoteUser != null) {
              request.addHeader(remoteUserHeader,remoteUser);
            }
          }
        }
      }
);
    }
  }
}
 

Example 44

From project proxydroid, under directory /src/com/github/droidfu/http/.

Source file: BetterHttp.java

  17 
vote

public static void setupHttpClient(){
  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);
  HttpProtocolParams.setVersion(httpParams,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setUserAgent(httpParams,httpUserAgent);
  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);
  httpClient=new DefaultHttpClient(cm,httpParams);
}
 

Example 45

From project QuotaForAndroid, under directory /Quota/src/com/southfreo/quota/utils/.

Source file: HttpHelper.java

  17 
vote

public static DefaultHttpClient TelstraClient(){
  HttpParams myParams=new BasicHttpParams();
  int defaultTimeOut=60 * 1000;
  HttpConnectionParams.setConnectionTimeout(myParams,defaultTimeOut);
  HttpConnectionParams.setSoTimeout(myParams,defaultTimeOut);
  HttpProtocolParams.setVersion(myParams,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(myParams,HTTP.DEFAULT_CONTENT_CHARSET);
  HttpProtocolParams.setUserAgent(myParams,"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6");
  TelstraStore client=new TelstraStore(UIManager.getInstance().myapp);
  client.setParams(myParams);
  return client;
}
 

Example 46

From project rain-workload-toolkit, under directory /thirdparty/httpcomponents-client-4.0.1/examples/org/apache/http/examples/conn/.

Source file: ManagerConnectDirect.java

  17 
vote

/** 
 * Performs general setup. This should be called only once.
 */
private final static void setup(){
  supportedSchemes=new SchemeRegistry();
  SocketFactory sf=PlainSocketFactory.getSocketFactory();
  supportedSchemes.register(new Scheme("http",sf,80));
  HttpParams params=new BasicHttpParams();
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setUseExpectContinue(params,false);
  defaultParameters=params;
}
 

Example 47

From project ratebeer-for-Android, under directory /RateBeerForAndroid/src/com/ratebeer/android/api/.

Source file: HttpHelper.java

  17 
vote

private static void ensureClient(){
  if (httpClient == null) {
    SchemeRegistry registry=new SchemeRegistry();
    registry.register(new Scheme("http",new PlainSocketFactory(),80));
    HttpParams httpparams=new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams,TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpparams,TIMEOUT);
    HttpProtocolParams.setUserAgent(httpparams,USER_AGENT);
    httpClient=new DefaultHttpClient(new ThreadSafeClientConnManager(httpparams,registry),httpparams);
  }
}
 

Example 48

From project ratebeerforandroid, under directory /RateBeerForAndroid/src/com/ratebeer/android/api/.

Source file: HttpHelper.java

  17 
vote

private static void ensureClient(){
  if (httpClient == null) {
    SchemeRegistry registry=new SchemeRegistry();
    registry.register(new Scheme("http",new PlainSocketFactory(),80));
    HttpParams httpparams=new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams,TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpparams,TIMEOUT);
    HttpProtocolParams.setUserAgent(httpparams,USER_AGENT);
    httpClient=new DefaultHttpClient(new ThreadSafeClientConnManager(httpparams,registry),httpparams);
  }
}
 

Example 49

From project ReGalAndroid, under directory /g2-java-client/src/main/java/net/dahanne/gallery/g2/java/client/business/.

Source file: G2Client.java

  17 
vote

private DefaultHttpClient createHttpClient(){
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",new FakeSocketFactory(),443));
  HttpParams params=new BasicHttpParams();
  params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS,30);
  params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE,new ConnPerRouteBean(30));
  params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE,false);
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  ClientConnectionManager cm=new ThreadSafeClientConnManager(params,schemeRegistry);
  return new DefaultHttpClient(cm,params);
}
 

Example 50

From project rest-assured, under directory /rest-assured/src/main/java/com/jayway/restassured/internal/http/.

Source file: HTTPBuilder.java

  17 
vote

public HTTPBuilder(boolean urlEncodingEnabled,EncoderConfig encoderConfig){
  super();
  HttpParams defaultParams=new BasicHttpParams();
  defaultParams.setParameter(CookieSpecPNames.DATE_PATTERNS,Arrays.asList("EEE, dd-MMM-yyyy HH:mm:ss z","EEE, dd MMM yyyy HH:mm:ss z"));
  this.client=new DefaultHttpClient(defaultParams);
  this.setContentEncoding(ContentEncoding.Type.GZIP,ContentEncoding.Type.DEFLATE);
  this.encoderConfig=encoderConfig == null ? new EncoderConfig() : encoderConfig;
  this.urlEncodingEnabled=urlEncodingEnabled;
}
 

Example 51

From project Rhybudd, under directory /src/net/networksaremadeofstring/rhybudd/.

Source file: ZenossAPIv2.java

  17 
vote

private void PrepareHTTPClient(){
  HttpParams params=new BasicHttpParams();
  client=new DefaultHttpClient();
  SchemeRegistry registry=new SchemeRegistry();
  registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  mgr=new ThreadSafeClientConnManager(params,registry);
  httpclient=new DefaultHttpClient(mgr,client.getParams());
}
 

Example 52

From project rozkladpkp-android, under directory /src/org/tyszecki/rozkladpkp/.

Source file: StationSearch.java

  17 
vote

public StationSearch(){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,2000);
  HttpConnectionParams.setSoTimeout(params,2000);
  client=new DefaultHttpClient(params);
  client.removeRequestInterceptorByClass(org.apache.http.protocol.RequestExpectContinue.class);
  client.removeRequestInterceptorByClass(org.apache.http.protocol.RequestUserAgent.class);
}
 

Example 53

From project SchoolPlanner4Untis, under directory /src/edu/htl3r/schoolplanner/backend/network/.

Source file: Network.java

  17 
vote

public Network(){
  initSSLSocketFactories();
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20000);
  HttpConnectionParams.setSoTimeout(params,10000);
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
  HttpProtocolParams.setUseExpectContinue(params,false);
  SchemeRegistry registry=new SchemeRegistry();
  ClientConnectionManager connman=new ThreadSafeClientConnManager(params,registry);
  client=new DefaultHttpClient(connman,params);
}
 

Example 54

From project ShortcutLink, under directory /src/org/bibimbap/shortcutlink/.

Source file: AndroidHttpClient.java

  17 
vote

/** 
 * Create a new HttpClient with reasonable defaults (which you can update).
 * @param userAgent to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  HttpConnectionParams.setConnectionTimeout(params,20 * 1000);
  HttpConnectionParams.setSoTimeout(params,20 * 1000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpClientParams.setRedirecting(params,false);
  HttpProtocolParams.setUserAgent(params,userAgent);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager manager=new ThreadSafeClientConnManager(params,schemeRegistry);
  return new AndroidHttpClient(manager,params);
}
 

Example 55

From project skalli, under directory /org.eclipse.skalli.core/src/main/java/org/eclipse/skalli/core/internal/destination/.

Source file: DestinationServiceImpl.java

  17 
vote

@Override public HttpClient getClient(URL url){
  if (!isSupportedProtocol(url)) {
    throw new IllegalArgumentException(MessageFormat.format("Protocol ''{0}'' is not suppported by this method",url.getProtocol()));
  }
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,CONNECT_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,READ_TIMEOUT);
  HttpConnectionParams.setTcpNoDelay(params,true);
  DefaultHttpClient client=new DefaultHttpClient(connectionManager,params);
  setProxy(client,url);
  setCredentials(client,url);
  return client;
}
 

Example 56

From project spark, under directory /spark-http-client/src/main/java/spark/protocol/.

Source file: ProtocolDataSource.java

  17 
vote

/** 
 * Creates a new thread-safe HTTP connection pool for use with a data source.
 * @param poolSize The size of the connection pool.
 * @return A new connection pool with the given size.
 */
private HttpClient createPooledClient(){
  HttpParams connMgrParams=new BasicHttpParams();
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme(HTTP_SCHEME,PlainSocketFactory.getSocketFactory(),HTTP_PORT));
  schemeRegistry.register(new Scheme(HTTPS_SCHEME,SSLSocketFactory.getSocketFactory(),HTTPS_PORT));
  ConnManagerParams.setMaxTotalConnections(connMgrParams,poolSize);
  ConnManagerParams.setMaxConnectionsPerRoute(connMgrParams,new ConnPerRouteBean(poolSize));
  ClientConnectionManager ccm=new ThreadSafeClientConnManager(connMgrParams,schemeRegistry);
  HttpParams httpParams=new BasicHttpParams();
  HttpProtocolParams.setUseExpectContinue(httpParams,false);
  ConnManagerParams.setTimeout(httpParams,acquireTimeout * 1000);
  return new DefaultHttpClient(ccm,httpParams);
}
 

Example 57

From project spring-android, under directory /spring-android-rest-template/src/main/java/org/springframework/http/client/.

Source file: HttpComponentsClientHttpRequestFactory.java

  17 
vote

/** 
 * Create a new instance of the  {@code HttpComponentsClientHttpRequestFactory} with a default {@link HttpClient}that uses a default  {@link ThreadSafeClientConnManager}.
 */
public HttpComponentsClientHttpRequestFactory(){
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  HttpParams params=new BasicHttpParams();
  ThreadSafeClientConnManager connectionManager=new ThreadSafeClientConnManager(params,schemeRegistry);
  ConnManagerParams.setMaxTotalConnections(params,DEFAULT_MAX_TOTAL_CONNECTIONS);
  ConnManagerParams.setMaxConnectionsPerRoute(params,new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS_PER_ROUTE));
  this.httpClient=new DefaultHttpClient(connectionManager,null);
  setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
}
 

Example 58

From project subsonic, under directory /subsonic-android/src/github/daneren2005/dsub/service/.

Source file: RESTMusicService.java

  17 
vote

public RESTMusicService(){
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,20);
  ConnManagerParams.setMaxConnectionsPerRoute(params,new ConnPerRouteBean(20));
  HttpConnectionParams.setConnectionTimeout(params,SOCKET_CONNECT_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,SOCKET_READ_TIMEOUT_DEFAULT);
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",createSSLSocketFactory(),443));
  connManager=new ThreadSafeClientConnManager(params,schemeRegistry);
  httpClient=new DefaultHttpClient(connManager,params);
}
 

Example 59

From project Subsonic-Android, under directory /src/net/sourceforge/subsonic/androidapp/service/.

Source file: RESTMusicService.java

  17 
vote

public RESTMusicService(){
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,20);
  ConnManagerParams.setMaxConnectionsPerRoute(params,new ConnPerRouteBean(20));
  HttpConnectionParams.setConnectionTimeout(params,SOCKET_CONNECT_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,SOCKET_READ_TIMEOUT_DEFAULT);
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",createSSLSocketFactory(),443));
  connManager=new ThreadSafeClientConnManager(params,schemeRegistry);
  httpClient=new DefaultHttpClient(connManager,params);
}
 

Example 60

From project subsonic_1, under directory /subsonic-android/src/net/sourceforge/subsonic/androidapp/service/.

Source file: RESTMusicService.java

  17 
vote

public RESTMusicService(){
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,20);
  ConnManagerParams.setMaxConnectionsPerRoute(params,new ConnPerRouteBean(20));
  HttpConnectionParams.setConnectionTimeout(params,SOCKET_CONNECT_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,SOCKET_READ_TIMEOUT_DEFAULT);
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",createSSLSocketFactory(),443));
  connManager=new ThreadSafeClientConnManager(params,schemeRegistry);
  httpClient=new DefaultHttpClient(connManager,params);
}
 

Example 61

From project subsonic_2, under directory /subsonic-android/src/net/sourceforge/subsonic/androidapp/service/.

Source file: RESTMusicService.java

  17 
vote

public RESTMusicService(){
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,20);
  ConnManagerParams.setMaxConnectionsPerRoute(params,new ConnPerRouteBean(20));
  HttpConnectionParams.setConnectionTimeout(params,SOCKET_CONNECT_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,SOCKET_READ_TIMEOUT_DEFAULT);
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",createSSLSocketFactory(),443));
  connManager=new ThreadSafeClientConnManager(params,schemeRegistry);
  httpClient=new DefaultHttpClient(connManager,params);
}
 

Example 62

From project Supersonic, under directory /subsonic-android/src/net/sourceforge/subsonic/androidapp/service/.

Source file: RESTMusicService.java

  17 
vote

public RESTMusicService(){
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,20);
  ConnManagerParams.setMaxConnectionsPerRoute(params,new ConnPerRouteBean(20));
  HttpConnectionParams.setConnectionTimeout(params,SOCKET_CONNECT_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,SOCKET_READ_TIMEOUT_DEFAULT);
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",createSSLSocketFactory(),443));
  connManager=new ThreadSafeClientConnManager(params,schemeRegistry);
  httpClient=new DefaultHttpClient(connManager,params);
}
 

Example 63

From project 4308Cirrus, under directory /tendril-android-lib/src/main/java/edu/colorado/cs/cirrus/android/.

Source file: HttpUtils.java

  16 
vote

public static HttpClient getNewHttpClient(){
  try {
    KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null,null);
    SSLSocketFactory sf=new EasySSLSocketFactory(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);
    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);
    return new DefaultHttpClient(ccm,params);
  }
 catch (  Exception e) {
    return new DefaultHttpClient();
  }
}
 

Example 64

From project android-bankdroid, under directory /src/eu/nullbyte/android/urllib/.

Source file: Urllib.java

  16 
vote

public Urllib(boolean acceptInvalidCertificates,boolean allowCircularRedirects){
  this.acceptInvalidCertificates=acceptInvalidCertificates;
  this.headers=new HashMap<String,String>();
  HttpParams params=new BasicHttpParams();
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(params,this.charset);
  params.setBooleanParameter("http.protocol.expect-continue",false);
  if (allowCircularRedirects)   params.setBooleanParameter("http.protocol.allow-circular-redirects",true);
  if (acceptInvalidCertificates) {
    SchemeRegistry registry=new SchemeRegistry();
    registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
    registry.register(new Scheme("https",new EasySSLSocketFactory(),443));
    ClientConnectionManager manager=new ThreadSafeClientConnManager(params,registry);
    httpclient=new DefaultHttpClient(manager,params);
  }
 else {
    SchemeRegistry registry=new SchemeRegistry();
    registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
    registry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
    ClientConnectionManager manager=new ThreadSafeClientConnManager(params,registry);
    httpclient=new DefaultHttpClient(manager,params);
  }
  context=new BasicHttpContext();
}
 

Example 65

From project androidquery, under directory /src/com/androidquery/callback/.

Source file: AbstractAjaxCallback.java

  16 
vote

private static DefaultHttpClient getClient(){
  if (client == null || !REUSE_CLIENT) {
    AQUtility.debug("creating http client");
    HttpParams httpParams=new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,NET_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams,NET_TIMEOUT);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams,new ConnPerRouteBean(25));
    HttpConnectionParams.setSocketBufferSize(httpParams,8192);
    SchemeRegistry registry=new SchemeRegistry();
    registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
    registry.register(new Scheme("https",ssf == null ? SSLSocketFactory.getSocketFactory() : ssf,443));
    ThreadSafeClientConnManager cm=new ThreadSafeClientConnManager(httpParams,registry);
    client=new DefaultHttpClient(cm,httpParams);
  }
  return client;
}
 

Example 66

From project andstatus, under directory /src/org/andstatus/app/net/.

Source file: ConnectionOAuth.java

  16 
vote

public ConnectionOAuth(MyAccount ma){
  super(ma);
  mOauthBaseUrl=ma.getOauthBaseUrl();
  HttpParams parameters=new BasicHttpParams();
  HttpProtocolParams.setVersion(parameters,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(parameters,HTTP.DEFAULT_CONTENT_CHARSET);
  HttpProtocolParams.setUseExpectContinue(parameters,false);
  HttpConnectionParams.setTcpNoDelay(parameters,true);
  HttpConnectionParams.setSocketBufferSize(parameters,8192);
  SchemeRegistry schReg=new SchemeRegistry();
  schReg.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  ClientConnectionManager tsccm=new ThreadSafeClientConnManager(parameters,schReg);
  mClient=new DefaultHttpClient(tsccm,parameters);
  OAuthKeys oak=new OAuthKeys(ma.getOriginId());
  mConsumer=new CommonsHttpOAuthConsumer(oak.getConsumerKey(),oak.getConsumerSecret());
  mProvider=new CommonsHttpOAuthProvider(getApiUrl(apiEnum.OAUTH_REQUEST_TOKEN),getApiUrl(apiEnum.OAUTH_ACCESS_TOKEN),getApiUrl(apiEnum.OAUTH_AUTHORIZE));
  mProvider.setOAuth10a(true);
  if (ma.dataContains(ConnectionOAuth.USER_TOKEN) && ma.dataContains(ConnectionOAuth.USER_SECRET)) {
    setAuthInformation(ma.getDataString(ConnectionOAuth.USER_TOKEN,null),ma.getDataString(ConnectionOAuth.USER_SECRET,null));
  }
}
 

Example 67

From project andtweet, under directory /src/com/xorcode/andtweet/net/.

Source file: ConnectionOAuth.java

  16 
vote

public ConnectionOAuth(SharedPreferences sp){
  super(sp);
  HttpParams parameters=new BasicHttpParams();
  HttpProtocolParams.setVersion(parameters,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(parameters,HTTP.DEFAULT_CONTENT_CHARSET);
  HttpProtocolParams.setUseExpectContinue(parameters,false);
  HttpConnectionParams.setTcpNoDelay(parameters,true);
  HttpConnectionParams.setSocketBufferSize(parameters,8192);
  SchemeRegistry schReg=new SchemeRegistry();
  schReg.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  ClientConnectionManager tsccm=new ThreadSafeClientConnManager(parameters,schReg);
  mClient=new DefaultHttpClient(tsccm,parameters);
  mConsumer=new CommonsHttpOAuthConsumer(OAuthKeys.TWITTER_CONSUMER_KEY,OAuthKeys.TWITTER_CONSUMER_SECRET);
  loadSavedKeys(sp);
}
 

Example 68

From project AquaNotesTest, under directory /src/com/google/android/apps/iosched/service/.

Source file: SyncService.java

  16 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.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;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 69

From project be.norio.twunch.android, under directory /src/be/norio/twunch/android/service/.

Source file: SyncService.java

  16 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.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;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 70

From project cloudify, under directory /rest-client/src/main/java/org/cloudifysource/restclient/.

Source file: GSRestClient.java

  16 
vote

/** 
 * Returns a HTTP client configured to use SSL.
 * @return HTTP client configured to use SSL
 * @throws RestException Reporting different failures while creating the HTTP client
 */
public final DefaultHttpClient getSSLHttpClient() throws RestException {
  try {
    final KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null,null);
    final SSLSocketFactory sf=new RestSSLSocketFactory(trustStore);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    final HttpParams params=new BasicHttpParams();
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
    final SchemeRegistry registry=new SchemeRegistry();
    registry.register(new Scheme(HTTPS,sf,url.getPort()));
    final ClientConnectionManager ccm=new ThreadSafeClientConnManager(params,registry);
    return new DefaultHttpClient(ccm,params);
  }
 catch (  final KeyStoreException e) {
    throw new RestException(e);
  }
catch (  final NoSuchAlgorithmException e) {
    throw new RestException(e);
  }
catch (  final CertificateException e) {
    throw new RestException(e);
  }
catch (  final IOException e) {
    throw new RestException(e);
  }
catch (  final KeyManagementException e) {
    throw new RestException(e);
  }
catch (  final UnrecoverableKeyException e) {
    throw new RestException(e);
  }
}
 

Example 71

From project conference-mobile-app, under directory /android-app/src/com/google/android/apps/iosched/service/.

Source file: SyncService.java

  16 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.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;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 72

From project couchdb-lucene, under directory /src/main/java/com/github/rnewson/couchdb/lucene/.

Source file: HttpClientFactory.java

  16 
vote

public static synchronized HttpClient getInstance() throws MalformedURLException {
  if (instance == null) {
    final HttpParams params=new BasicHttpParams();
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUseExpectContinue(params,false);
    HttpConnectionParams.setTcpNoDelay(params,true);
    HttpConnectionParams.setStaleCheckingEnabled(params,false);
    ConnManagerParams.setMaxTotalConnections(params,1000);
    ConnManagerParams.setMaxConnectionsPerRoute(params,new ConnPerRouteBean(1000));
    final SchemeRegistry schemeRegistry=new SchemeRegistry();
    schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),5984));
    schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
    final ClientConnectionManager cm=new ShieldedClientConnManager(new ThreadSafeClientConnManager(params,schemeRegistry));
    instance=new DefaultHttpClient(cm,params);
    if (INI != null) {
      final CredentialsProvider credsProvider=new BasicCredentialsProvider();
      final Iterator<?> it=INI.getKeys();
      while (it.hasNext()) {
        final String key=(String)it.next();
        if (!key.startsWith("lucene.") && key.endsWith(".url")) {
          final URL url=new URL(INI.getString(key));
          if (url.getUserInfo() != null) {
            credsProvider.setCredentials(new AuthScope(url.getHost(),url.getPort()),new UsernamePasswordCredentials(url.getUserInfo()));
          }
        }
      }
      instance.setCredentialsProvider(credsProvider);
      instance.addRequestInterceptor(new PreemptiveAuthenticationRequestInterceptor(),0);
    }
  }
  return instance;
}
 

Example 73

From project couchdb4j, under directory /src/java/com/fourspaces/couchdb/.

Source file: Session.java

  16 
vote

/** 
 * Constructor for obtaining a Session with an HTTP-AUTH username/password and (optionally) a secure connection This isn't supported by CouchDB - you need a proxy in front to use this
 * @param host - hostname
 * @param port - port to use
 * @param user - username
 * @param pass - password
 * @param secure  - use an SSL connection?
 */
public Session(String host,int port,String user,String pass,boolean usesAuth,boolean secure){
  this.host=host;
  this.port=port;
  this.user=user;
  this.pass=pass;
  this.usesAuth=usesAuth;
  this.secure=secure;
  httpParams=new BasicHttpParams();
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ThreadSafeClientConnManager connManager=new ThreadSafeClientConnManager(httpParams,schemeRegistry);
  DefaultHttpClient defaultClient=new DefaultHttpClient(connManager,httpParams);
  if (user != null) {
    defaultClient.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(user,pass));
  }
  this.httpClient=defaultClient;
  setUserAgent("couchdb4j");
  setSocketTimeout((30 * 1000));
  setConnectionTimeout((15 * 1000));
}
 

Example 74

From project dccsched, under directory /src/com/underhilllabs/dccsched/service/.

Source file: SyncService.java

  16 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.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;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 75

From project dcnyc10-android, under directory /android/src/com/lullabot/android/apps/iosched/service/.

Source file: SyncService.java

  16 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.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;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 76

From project DeskSMS, under directory /DeskSMS/src/com/koushikdutta/desktopsms/.

Source file: TickleServiceHelper.java

  16 
vote

static String getCookie(final Context context) throws ClientProtocolException, IOException, URISyntaxException {
  Settings settings=Settings.getInstance(context);
  final String authToken=settings.getString("web_connect_auth_token");
  if (authToken == null)   return null;
  Log.i(LOGTAG,authToken);
  Log.i(LOGTAG,"getting cookie");
  DefaultHttpClient client=new DefaultHttpClient();
  String continueURL=ServiceHelper.BASE_URL;
  URI uri=new URI(ServiceHelper.AUTH_URL + "?continue=" + URLEncoder.encode(continueURL,"UTF-8")+ "&auth="+ authToken);
  HttpGet method=new HttpGet(uri);
  final HttpParams getParams=new BasicHttpParams();
  HttpClientParams.setRedirecting(getParams,false);
  method.setParams(getParams);
  HttpResponse res=client.execute(method);
  Header[] headers=res.getHeaders("Set-Cookie");
  if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) {
    return null;
  }
  String ascidCookie=null;
  for (  Header header : headers) {
    if (header.getValue().indexOf("ACSID=") >= 0) {
      String value=header.getValue();
      String[] pairs=value.split(";");
      ascidCookie=pairs[0];
    }
  }
  settings.setString("Cookie",ascidCookie);
  return ascidCookie;
}
 

Example 77

From project devoxx-france-android-in-fine, under directory /src/com/infine/android/devoxx/service/.

Source file: RestService.java

  16 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * 1000);
  HttpConnectionParams.setSoTimeout(params,20 * 1000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.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;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 78

From project DiscogsForAndroid, under directory /src/com/discogs/services/.

Source file: NetworkHelper.java

  16 
vote

private void initHTTPClient(){
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  HttpParams params=new BasicHttpParams();
  HttpProtocolParams.setContentCharset(params,"utf-8");
  params.setBooleanParameter("http.protocol.expect-continue",false);
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(params,HTTP.DEFAULT_CONTENT_CHARSET);
  HttpProtocolParams.setUseExpectContinue(params,true);
  ThreadSafeClientConnManager connectionManager=new ThreadSafeClientConnManager(params,schemeRegistry);
  httpClient=new DefaultHttpClient(connectionManager,params);
  httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3,false));
  httpClient.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    final HttpRequest request,    final HttpContext context) throws HttpException, IOException {
      if (!request.containsHeader("Accept-Encoding")) {
        request.addHeader("Accept-Encoding","gzip");
      }
    }
  }
);
  httpClient.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;
            }
          }
        }
      }
    }
  }
);
}
 

Example 79

From project fed4j, under directory /src/main/java/com/jute/fed4j/engine/component/http/.

Source file: HttpDispatcherImpl_Jakarta.java

  16 
vote

public void run(HttpComponent component){
  this.commponent=component;
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,component.connectTimeout);
  HttpConnectionParams.setSoTimeout(params,component.readTimeout);
  try {
    this.init(component);
    HttpClient httpclient=new MyHttpClient(getConnectionManager(params,component.enablePersistentConnection),params);
    if (component.enableProxy && "http".equals(component.proxyType)) {
      HttpHost proxy=new HttpHost(component.proxyHost,component.proxyPort,component.proxyType);
      httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
    }
    HttpUriRequest request=new HttpRequest(component.method,component.uri);
    MyHttpResponseHandler responseHandler=new MyHttpResponseHandler(component.responseCharset);
    String body=httpclient.execute(request,responseHandler);
    this.onResponse(component,responseHandler.code,body);
  }
 catch (  SocketTimeoutException e) {
    onException(component,-2," socket timeout error occurs: " + e.getMessage());
  }
catch (  ClientProtocolException e) {
    onException(component,-3," error resposed from server: " + e.getMessage());
  }
catch (  IOException e) {
    onException(component,-4," error occurs during dispatch: " + e.getMessage());
  }
catch (  Exception e) {
    onException(component,-5,"error occurs during parsing xml:" + e.getMessage());
  }
}
 

Example 80

From project friendica-for-android, under directory /mw-android-friendica-01/src/de/wikilab/android/friendica01/.

Source file: TwAjax.java

  16 
vote

public DefaultHttpClient getNewHttpClient(){
  if (ignoreSSLCerts) {
    try {
      KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null,null);
      SSLSocketFactory sf=new IgnoreCertsSSLSocketFactory(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);
      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);
      return new DefaultHttpClient(ccm,params);
    }
 catch (    Exception e) {
      return new DefaultHttpClient();
    }
  }
 else {
    return new DefaultHttpClient();
  }
}
 

Example 81

From project Gaggle, under directory /src/com/geeksville/location/.

Source file: LeonardoUpload.java

  16 
vote

/** 
 * Upload a flight to Leonardo
 * @param username
 * @param password
 * @param postURL
 * @param shortFilename
 * @param igcFile we will take care of closing this stram
 * @return null for success, otherwise a string description of the problem
 * @throws IOException
 */
public static String upload(String username,String password,String postURL,int competitionClass,String shortFilename,String igcFile,int connectionTimeout,int operationTimeout) throws IOException {
  int i=shortFilename.lastIndexOf('.');
  if (i >= 1)   shortFilename=shortFilename.substring(0,i);
  String sCompetitionClass=String.valueOf(competitionClass);
  HttpParams httpParameters=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(httpParameters,connectionTimeout);
  HttpConnectionParams.setSoTimeout(httpParameters,operationTimeout);
  HttpClient httpclient=new DefaultHttpClient(httpParameters);
  httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);
  HttpPost httppost=new HttpPost(postURL);
  List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
  nameValuePairs.add(new BasicNameValuePair("user",username));
  nameValuePairs.add(new BasicNameValuePair("pass",password));
  nameValuePairs.add(new BasicNameValuePair("igcfn",shortFilename));
  nameValuePairs.add(new BasicNameValuePair("Klasse",sCompetitionClass));
  nameValuePairs.add(new BasicNameValuePair("IGCigcIGC",igcFile));
  httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  HttpResponse response=httpclient.execute(httppost);
  HttpEntity entity=response.getEntity();
  String resp=EntityUtils.toString(entity);
  if (resp.contains("flight scored"))   resp=null;
 else {
    int bodLoc=resp.indexOf("<body>");
    if (bodLoc >= 0)     resp=resp.substring(bodLoc + 6);
    int probLoc=resp.indexOf("problem");
    if (probLoc >= 0)     resp=resp.substring(probLoc + 7);
    if (resp.startsWith("<br>"))     resp=resp.substring(4);
    int markLoc=resp.indexOf('<');
    if (markLoc >= 0)     resp=resp.substring(0,markLoc);
    resp=resp.trim();
  }
  return resp;
}
 

Example 82

From project gddsched2, under directory /trunk/android/src/com/google/android/apps/iosched2/service/.

Source file: SyncService.java

  16 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.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;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 83

From project GraduationProject, under directory /G-Card/src/Hello/Tab/Widget/.

Source file: AppEngineClient.java

  16 
vote

private HttpResponse makeRequestNoRetry(String urlPath,List<NameValuePair> params,boolean newToken) throws Exception {
  Account account=new Account(mAccountName,"com.google");
  String authToken=getAuthToken(mContext,account);
  if (newToken) {
    AccountManager accountManager=AccountManager.get(mContext);
    accountManager.invalidateAuthToken(account.type,authToken);
    authToken=getAuthToken(mContext,account);
  }
  DefaultHttpClient client=new DefaultHttpClient();
  String continueURL=BASE_URL;
  URI uri=new URI(AUTH_URL + "?continue=" + URLEncoder.encode(continueURL,"UTF-8")+ "&auth="+ authToken);
  HttpGet method=new HttpGet(uri);
  final HttpParams getParams=new BasicHttpParams();
  HttpClientParams.setRedirecting(getParams,false);
  method.setParams(getParams);
  HttpResponse res=client.execute(method);
  Header[] headers=res.getHeaders("Set-Cookie");
  if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) {
    return res;
  }
  String ascidCookie=null;
  for (  Header header : headers) {
    if (header.getValue().indexOf("ACSID=") >= 0) {
      String value=header.getValue();
      String[] pairs=value.split(";");
      ascidCookie=pairs[0];
    }
  }
  uri=new URI(BASE_URL + urlPath);
  HttpPost post=new HttpPost(uri);
  UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"UTF-8");
  post.setEntity(entity);
  post.setHeader("Cookie",ascidCookie);
  post.setHeader("X-Same-Domain","1");
  res=client.execute(post);
  return res;
}
 

Example 84

From project gxa, under directory /annotator/src/main/java/uk/ac/ebi/gxa/annotator/loader/.

Source file: URLContentLoader.java

  16 
vote

public File getContentAsFile(String url,File file) throws AnnotationException {
  HttpGet httpGet=new HttpGet(url);
  final HttpParams params=new BasicHttpParams();
  HttpClientParams.setRedirecting(params,true);
  httpGet.setParams(params);
  FileOutputStream out=null;
  try {
    HttpResponse response=httpClient.execute(httpGet);
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
      throw new AnnotationException("Failed to connect to: " + url + " "+ response.getStatusLine());
    }
    HttpEntity entity=response.getEntity();
    final long responseContentLength=entity.getContentLength();
    out=new FileOutputStream(file);
    entity.writeTo(out);
    out.close();
    final long actualLength=file.length();
    if (actualLength < responseContentLength) {
      log.error("Not all data are loaded actual size {} expected size {}",actualLength,responseContentLength);
      throw new AnnotationException("Failed to download all annotation data from: " + url + " expected size="+ responseContentLength+ " actual="+ actualLength+ ". Please try again!");
    }
  }
 catch (  IOException e) {
    throw new AnnotationException("Fatal transport error when reading from " + url,e);
  }
 finally {
    closeQuietly(out);
  }
  return file;
}
 

Example 85

From project httpcache4j, under directory /resolvers/resolvers-httpcomponents-httpclient/src/main/java/org/codehaus/httpcache4j/resolver/.

Source file: HTTPClientResponseResolver.java

  16 
vote

public HTTPClientResponseResolver(HttpClient httpClient,ResolverConfiguration configuration){
  super(configuration);
  this.httpClient=httpClient;
  HTTPHost proxyHost=getProxyAuthenticator().getConfiguration().getHost();
  HttpParams params=httpClient.getParams();
  if (params == null) {
    params=new BasicHttpParams();
    if (httpClient instanceof DefaultHttpClient) {
      ((DefaultHttpClient)httpClient).setParams(params);
    }
  }
  if (proxyHost != null) {
    HttpHost host=new HttpHost(proxyHost.getHost(),proxyHost.getPort(),proxyHost.getScheme());
    params.setParameter(ConnRoutePNames.DEFAULT_PROXY,host);
  }
  params.setParameter(CoreProtocolPNames.USER_AGENT,getConfiguration().getUserAgent());
}
 

Example 86

From project iosched, under directory /android/src/com/google/android/apps/iosched/service/.

Source file: SyncService.java

  16 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.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;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 87

From project iosched2011, under directory /android/src/com/google/android/apps/iosched/service/.

Source file: SyncService.java

  16 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.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;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 88

From project iosched_1, under directory /src/com/google/android/apps/iosched/service/.

Source file: SyncService.java

  16 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.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;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 89

From project iosched_2, under directory /android/src/com/google/android/apps/iosched/service/.

Source file: SyncService.java

  16 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.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;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 90

From project iSpace, under directory /base/httpcrawler/src/main/java/com/villemos/ispace/httpcrawler/.

Source file: HttpClientConfigurer.java

  16 
vote

public static HttpClient setupClient(boolean ignoreAuthenticationFailure,String domain,Integer port,String proxyHost,Integer proxyPort,String authUser,String authPassword,CookieStore cookieStore) throws NoSuchAlgorithmException, KeyManagementException {
  DefaultHttpClient client=null;
  if (ignoreAuthenticationFailure) {
    SSLContext sslContext=SSLContext.getInstance("SSL");
    sslContext.init(null,new TrustManager[]{new EasyX509TrustManager()},new SecureRandom());
    SchemeRegistry schemeRegistry=new SchemeRegistry();
    SSLSocketFactory sf=new SSLSocketFactory(sslContext);
    Scheme httpsScheme=new Scheme("https",sf,443);
    schemeRegistry.register(httpsScheme);
    SocketFactory sfa=new PlainSocketFactory();
    Scheme httpScheme=new Scheme("http",sfa,80);
    schemeRegistry.register(httpScheme);
    HttpParams params=new BasicHttpParams();
    ClientConnectionManager cm=new SingleClientConnManager(params,schemeRegistry);
    client=new DefaultHttpClient(cm,params);
  }
 else {
    client=new DefaultHttpClient();
  }
  if (proxyHost != null && proxyPort != null) {
    HttpHost proxy=new HttpHost(proxyHost,proxyPort);
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
  }
 else {
    ProxySelectorRoutePlanner routePlanner=new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(),ProxySelector.getDefault());
    client.setRoutePlanner(routePlanner);
  }
  if (authUser != null && authPassword != null) {
    client.getCredentialsProvider().setCredentials(new AuthScope(domain,port),new UsernamePasswordCredentials(authUser,authPassword));
  }
  client.setCookieStore(cookieStore);
  client.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BEST_MATCH);
  return client;
}
 

Example 91

From project janbanery, under directory /janbanery-android/src/main/java/pl/project13/janbanery/android/rest/.

Source file: AndroidCompatibleRestClient.java

  16 
vote

public DefaultHttpClient getClient(){
  DefaultHttpClient ret;
  HttpParams params=new BasicHttpParams();
  HttpProtocolParams.setVersion(params,new ProtocolVersion("HTTP",1,1));
  HttpProtocolParams.setContentCharset(params,"UTF-8");
  params.setBooleanParameter("http.protocol.expect-continue",false);
  SchemeRegistry registry=new SchemeRegistry();
  registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  final SSLSocketFactory sslSocketFactory=SSLSocketFactory.getSocketFactory();
  sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier());
  registry.register(new Scheme("https",sslSocketFactory,443));
  ThreadSafeClientConnManager manager=new ThreadSafeClientConnManager(params,registry);
  ret=new DefaultHttpClient(manager,params);
  return ret;
}
 

Example 92

From project Jenkins-Repository, under directory /jenkins-maven-plugin/src/main/java/com/nirima/jenkins/.

Source file: SimpleArtifactCopier.java

  16 
vote

private void init() throws URISyntaxException {
  URI targetURI=host.toURI();
  targetHost=new HttpHost(targetURI.getHost(),targetURI.getPort());
  params=new BasicHttpParams();
  params.setParameter(HttpProtocolParams.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
  params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE,false);
  params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK,false);
  params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE,8 * 1024);
  httpexecutor=new HttpRequestExecutor();
  httpproc=new BasicHttpProcessor();
  httpproc.addInterceptor(new RequestContent());
  httpproc.addInterceptor(new RequestTargetHost());
  httpproc.addInterceptor(new RequestConnControl());
  httpproc.addInterceptor(new RequestUserAgent());
  httpproc.addInterceptor(new RequestExpectContinue());
  context=new BasicHttpContext();
  conn=new DefaultHttpClientConnection();
  connStrategy=new DefaultConnectionReuseStrategy();
}
 

Example 93

From project leviathan, under directory /httpclient/src/main/java/ar/com/zauber/leviathan/impl/.

Source file: BulkURIFetchers.java

  16 
vote

/** 
 * TODO we should load these from a Properties file. 
 */
private static HttpParams createHttpParams(){
  final HttpParams params=new BasicHttpParams();
  final HttpProtocolParamBean httpParams=new HttpProtocolParamBean(params);
  httpParams.setContentCharset("iso-8859-1");
  httpParams.setHttpElementCharset("iso-8859-1");
  httpParams.setUseExpectContinue(true);
  httpParams.setUserAgent("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6.4; " + "InfoPath.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; " + ".NET CLR 3.5.30729; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)");
  httpParams.setVersion(HttpVersion.HTTP_1_1);
  final HttpConnectionParamBean connectionParam=new HttpConnectionParamBean(params);
  connectionParam.setConnectionTimeout(10000);
  connectionParam.setSoTimeout(20000);
  connectionParam.setLinger(-1);
  connectionParam.setSocketBufferSize(8 * 1024);
  connectionParam.setStaleCheckingEnabled(true);
  connectionParam.setTcpNoDelay(true);
  final ClientParamBean clientParam=new ClientParamBean(params);
  clientParam.setHandleRedirects(true);
  clientParam.setRejectRelativeRedirect(false);
  clientParam.setMaxRedirects(10);
  clientParam.setAllowCircularRedirects(false);
  final ConnManagerParamBean connManagerParam=new ConnManagerParamBean(params);
  connManagerParam.setConnectionsPerRoute(new ConnPerRouteBean(5));
  connManagerParam.setMaxTotalConnections(100);
  final ConnManagerParamBean connConnectionParam=new ConnManagerParamBean(params);
  return params;
}
 

Example 94

From project lightbox-android-webservices, under directory /LightboxAndroidWebServices/src/com/lightbox/android/network/.

Source file: HttpHelper.java

  16 
vote

/** 
 * Create an HttpClient.
 * @return a properly set HttpClient
 */
private static DefaultHttpClient createHttpClient(){
  HttpParams params=new BasicHttpParams();
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme(STRING_HTTP,PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme(STRING_HTTPS,SSLSocketFactory.getSocketFactory(),443));
  HttpConnectionParams.setConnectionTimeout(params,HTTP_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,HTTP_TIMEOUT);
  ConnManagerParams.setTimeout(params,HTTP_TIMEOUT);
  HttpConnectionParams.setSocketBufferSize(params,SOCKET_BUFFER_SIZE);
  HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
  HttpProtocolParams.setHttpElementCharset(params,HTTP.UTF_8);
  HttpProtocolParams.setUserAgent(params,String.format(USER_AGENT_FORMAT_STRING,AndroidUtils.getApplicationLabel(),AndroidUtils.getVersionCode(),android.os.Build.VERSION.RELEASE,android.os.Build.MODEL));
  DefaultHttpClient client=new DefaultHttpClient(new ThreadSafeClientConnManager(params,schemeRegistry),params);
  enableGzipCompression(client);
  return client;
}
 

Example 95

From project LRJavaLib, under directory /src/com/navnorth/learningregistry/.

Source file: LRClient.java

  16 
vote

public static HttpClient getHttpClient(String scheme){
  if (scheme.equals("https")) {
    try {
      KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null,null);
      SSLSocketFactory sf=new SelfSignSSLSocketFactory(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);
      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);
      return new DefaultHttpClient(ccm,params);
    }
 catch (    Exception e) {
      return new DefaultHttpClient();
    }
  }
 else {
    return new DefaultHttpClient();
  }
}
 

Example 96

From project Maimonides, under directory /src/com/codeko/apps/maimonides/seneca/.

Source file: ClienteSeneca.java

  16 
vote

public HttpClient getCliente(){
  if (cliente == null) {
    try {
      SSLContext ctx=SSLContext.getInstance("TLS");
      X509TrustManager tm=new X509TrustManager(){
        @Override public void checkClientTrusted(        X509Certificate[] xcs,        String string) throws CertificateException {
        }
        @Override public void checkServerTrusted(        X509Certificate[] xcs,        String string) throws CertificateException {
        }
        @Override public X509Certificate[] getAcceptedIssuers(){
          return null;
        }
      }
;
      ctx.init(null,new TrustManager[]{tm},null);
      SSLSocketFactory ssf=new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      SchemeRegistry schemeRegistry=new SchemeRegistry();
      schemeRegistry.register(new Scheme("http",80,PlainSocketFactory.getSocketFactory()));
      schemeRegistry.register(new Scheme("https",443,ssf));
      HttpParams params=new BasicHttpParams();
      HttpProtocolParams.setUserAgent(params,"Mozilla/5.0 (X11; U; Linux i686; es-ES; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.04 (lucid) Firefox/3.6.12");
      ThreadSafeClientConnManager cm=new ThreadSafeClientConnManager(schemeRegistry);
      cm.setDefaultMaxPerRoute(10);
      cm.setMaxTotal(20);
      HttpConnectionParams.setConnectionTimeout(params,1000);
      cliente=new DefaultHttpClient(cm,params);
    }
 catch (    Exception ex) {
      Logger.getLogger(ClienteSeneca.class.getName()).log(Level.SEVERE,null,ex);
      setUltimoError("Error conectando con S?neca: " + ex.getLocalizedMessage());
      setUltimaExcepcion(ex);
    }
  }
  ThreadSafeClientConnManager man=(ThreadSafeClientConnManager)cliente.getConnectionManager();
  man.closeExpiredConnections();
  man.closeIdleConnections(10,TimeUnit.SECONDS);
  Logger.getLogger(ClienteSeneca.class.getName()).log(Level.INFO,"Hay {0} conexiones abiertas.",man.getConnectionsInPool());
  return cliente;
}
 

Example 97

From project MobiPerf, under directory /android/src/com/mobiperf/speedometer/.

Source file: Checkin.java

  16 
vote

/** 
 * Return an appropriately-configured HTTP client.
 */
private HttpClient getNewHttpClient(){
  DefaultHttpClient client;
  try {
    KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null,null);
    SSLSocketFactory sf=new MySSLSocketFactory(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);
    HttpConnectionParams.setConnectionTimeout(params,POST_TIMEOUT_MILLISEC);
    HttpConnectionParams.setSoTimeout(params,POST_TIMEOUT_MILLISEC);
    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);
    client=new DefaultHttpClient(ccm,params);
  }
 catch (  Exception e) {
    Logger.w("Unable to create SSL HTTP client",e);
    client=new DefaultHttpClient();
  }
  CookieStore store=new BasicCookieStore();
  store.addCookie(authCookie);
  client.setCookieStore(store);
  return client;
}
 

Example 98

From project moho, under directory /moho-impl/src/main/java/com/voxeo/moho/imified/.

Source file: IMifiedDriver.java

  16 
vote

@Override public void init(SpiFramework framework){
  _appEventSource=framework;
  HttpServlet servlet=framework.getHTTPController();
  if (servlet.getServletConfig().getInitParameter("imifiedApiURL") != null) {
    _imifiedApiURL=servlet.getServletConfig().getInitParameter("imifiedApiURL");
  }
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,20);
  ConnPerRouteBean connPerRoute=new ConnPerRouteBean(20);
  ConnManagerParams.setMaxConnectionsPerRoute(params,connPerRoute);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager cm=new ThreadSafeClientConnManager(params,schemeRegistry);
  _httpClient=new DefaultHttpClient(cm,params);
  _httpClient.setReuseStrategy(new DefaultConnectionReuseStrategy());
  _httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy(){
    public long getKeepAliveDuration(    HttpResponse response,    HttpContext context){
      HeaderElementIterator it=new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
      while (it.hasNext()) {
        HeaderElement he=it.nextElement();
        String param=he.getName();
        String value=he.getValue();
        if (value != null && param.equalsIgnoreCase("timeout")) {
          try {
            return Long.parseLong(value) * 1000;
          }
 catch (          NumberFormatException ex) {
          }
        }
      }
      return -1;
    }
  }
);
}
 

Example 99

From project MyHeath-Android, under directory /src/com/buaa/shortytall/network/.

Source file: AbstractNetWorkThread.java

  16 
vote

protected String executePost(List<BasicNameValuePair> pairs) throws ClientProtocolException, IOException {
  setUrl();
  if (mUrl == null) {
    return null;
  }
  HttpPost httpPost=new HttpPost(mUrl);
  httpPost.setEntity(new UrlEncodedFormEntity(pairs,HTTP.UTF_8));
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setSoTimeout(params,TIMEOUT);
  HttpConnectionParams.setConnectionTimeout(params,TIMEOUT);
  HttpClientParams.setRedirecting(params,false);
  if (mHttpClient == null) {
    mHttpClient=new DefaultHttpClient();
  }
  mHttpClient.setParams(params);
  DefaultCoookieStore cookieStore=DefaultCoookieStore.getInstance(MyHealth.getCurrentContext());
  mHttpClient.setCookieStore(cookieStore);
  HttpResponse response=mHttpClient.execute(httpPost);
  cookieStore.saveCookies(MyHealth.getCurrentContext());
  int statusCode=response.getStatusLine().getStatusCode();
  if (statusCode == 200) {
    return EntityUtils.toString(response.getEntity());
  }
  return null;
}
 

Example 100

From project netifera, under directory /platform/com.netifera.platform.net.http/com.netifera.platform.net.http.service/src/com/netifera/platform/net/http/service/.

Source file: AsynchronousHTTPClient.java

  16 
vote

public AsynchronousHTTPClient(TCPSocketLocator locator,EventListener connectionsListener,HttpRequestExecutionHandler requestHandler,final ILogger logger) throws IOReactorException {
  this.locator=locator;
  this.connectionsListener=connectionsListener;
  this.logger=logger;
  HttpParams params=new BasicHttpParams();
  params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,5000).setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,8 * 1024).setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,true).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,true).setParameter(CoreProtocolPNames.USER_AGENT,HTTPClient.DEFAULT_USER_AGENT);
  ioReactor=new DefaultConnectingIOReactor(2,params);
  BasicHttpProcessor httpproc=new BasicHttpProcessor();
  httpproc.addInterceptor(new RequestContent());
  httpproc.addInterceptor(new RequestConnControl());
  httpproc.addInterceptor(new RequestUserAgent());
  httpproc.addInterceptor(new RequestExpectContinue());
  BufferingHttpClientHandler handler=new BufferingHttpClientHandler(httpproc,requestHandler,new DefaultConnectionReuseStrategy(),params);
  handler.setEventListener(new ConnectionsListener());
  final IOEventDispatch ioEventDispatch=new DefaultClientIOEventDispatch(handler,params);
  Thread t=new Thread(new Runnable(){
    public void run(){
      try {
        ioReactor.execute(ioEventDispatch);
      }
 catch (      InterruptedIOException ex) {
      }
catch (      IOException e) {
        logger.error("I/O error",e);
      }
      logger.debug("Shutdown HTTP Client");
    }
  }
);
  t.setName("HTTP Client on " + locator);
  t.start();
}
 

Example 101

From project nuxeo-distribution, under directory /nuxeo-startup-wizard/src/main/java/org/nuxeo/wizard/download/.

Source file: PackageDownloader.java

  16 
vote

protected PackageDownloader(){
  SchemeRegistry registry=new SchemeRegistry();
  registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  registry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  HttpParams httpParams=new BasicHttpParams();
  HttpProtocolParams.setUseExpectContinue(httpParams,false);
  ConnManagerParams.setMaxTotalConnections(httpParams,NB_DOWNLOAD_THREADS);
  ConnManagerParams.setMaxConnectionsPerRoute(httpParams,new ConnPerRoute(){
    @Override public int getMaxForRoute(    HttpRoute arg0){
      return NB_DOWNLOAD_THREADS;
    }
  }
);
  ThreadSafeClientConnManager cm=new ThreadSafeClientConnManager(httpParams,registry);
  httpClient=new DefaultHttpClient(cm,httpParams);
}
 

Example 102

From project OpenBike, under directory /src/fr/openbike/android/service/.

Source file: SyncService.java

  16 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.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;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 103

From project OpenMEAP, under directory /java-shared/openmeap-shared-jdk5/src/com/openmeap/util/.

Source file: SSLUtils.java

  16 
vote

static public HttpClient getRelaxedSSLVerificationHttpClient(){
  try {
    KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null,null);
    SSLSocketFactory sf=new MySSLSocketFactory(trustStore);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    HttpParams params=new BasicHttpParams();
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params,FormConstants.CHAR_ENC_DEFAULT);
    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);
    return new DefaultHttpClient(ccm,params);
  }
 catch (  Exception e) {
    return new DefaultHttpClient();
  }
}
 

Example 104

From project osgi-tests, under directory /test/glassfish-derby/src/test/java/org/ancoron/osgi/test/glassfish/.

Source file: GlassfishDerbyTest.java

  16 
vote

protected DefaultHttpClient getHTTPClient() throws NoSuchAlgorithmException, KeyManagementException {
  SSLContext sslContext=SSLContext.getInstance("SSL");
  sslContext.init(null,new TrustManager[]{new X509TrustManager(){
    @Override public X509Certificate[] getAcceptedIssuers(){
      System.out.println("getAcceptedIssuers =============");
      return null;
    }
    @Override public void checkClientTrusted(    X509Certificate[] certs,    String authType){
      System.out.println("checkClientTrusted =============");
    }
    @Override public void checkServerTrusted(    X509Certificate[] certs,    String authType){
      System.out.println("checkServerTrusted =============");
    }
  }
},new SecureRandom());
  SSLSocketFactory sf=new SSLSocketFactory(sslContext,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  Scheme httpsScheme=new Scheme("https",8181,sf);
  PlainSocketFactory plain=new PlainSocketFactory();
  Scheme httpScheme=new Scheme("http",8080,plain);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(httpsScheme);
  schemeRegistry.register(httpScheme);
  HttpParams params=new BasicHttpParams();
  ThreadSafeClientConnManager cm=new ThreadSafeClientConnManager(schemeRegistry);
  cm.setMaxTotal(200);
  cm.setDefaultMaxPerRoute(20);
  DefaultHttpClient httpClient=new DefaultHttpClient(cm,params);
  httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
  httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,"UTF-8");
  return httpClient;
}
 

Example 105

From project PageTurner, under directory /src/main/java/net/nightwhistler/pageturner/activity/.

Source file: CatalogActivity.java

  16 
vote

private void loadImageLink(Map<String,byte[]> cache,Link imageLink,String baseUrl) throws IOException {
  HttpParams httpParams=new BasicHttpParams();
  DefaultHttpClient client=new DefaultHttpClient(httpParams);
  client.getCredentialsProvider().setCredentials(new AuthScope(null,-1),new UsernamePasswordCredentials(user,password));
  if (imageLink != null) {
    String href=imageLink.getHref();
    if (cache.containsKey(href)) {
      imageLink.setBinData(cache.get(href));
    }
 else {
      String target=new URL(new URL(baseUrl),href).toString();
      LOG.info("Downloading image: " + target);
      HttpResponse resp=client.execute(new HttpGet(target));
      imageLink.setBinData(EntityUtils.toByteArray(resp.getEntity()));
      cache.put(href,imageLink.getBinData());
    }
  }
}
 

Example 106

From project Pitbull, under directory /pitbull-core/src/test/java/org/jboss/pitbull/test/.

Source file: SslEchoTest.java

  16 
vote

private static DefaultHttpClient createHttpClient(int port){
  try {
    java.lang.System.setProperty("sun.security.ssl.allowUnsafeRenegotiation","true");
    X509TrustManager trustManager=new X509TrustManager(){
      public void checkClientTrusted(      X509Certificate[] chain,      String authType) throws CertificateException {
      }
      public void checkServerTrusted(      X509Certificate[] chain,      String authType) throws CertificateException {
      }
      public X509Certificate[] getAcceptedIssuers(){
        return null;
      }
    }
;
    SSLContext sslContext=SSLContext.getInstance("SSL");
    sslContext.init(null,new TrustManager[]{trustManager},new SecureRandom());
    SSLSocketFactory sf=new SSLSocketFactory(sslContext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme httpsScheme=new Scheme("https",sf,port);
    SchemeRegistry schemeRegistry=new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    HttpParams params=new BasicHttpParams();
    ClientConnectionManager cm=new SingleClientConnManager(params,schemeRegistry);
    return new DefaultHttpClient(cm,params);
  }
 catch (  Exception ex) {
    return null;
  }
}
 

Example 107

From project ROM-Updater, under directory /src/org/elegosproject/romupdater/.

Source file: DownloadManager.java

  16 
vote

public static boolean checkHttpFile(String url){
  try {
    HttpParams httpParameters=new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters,3000);
    Log.i(TAG,"Testing " + url + "...");
    URL theUrl=new URL(url);
    HttpURLConnection connection=(HttpURLConnection)theUrl.openConnection();
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
      connection.disconnect();
    }
 else {
      Log.i(TAG,"HTTP Response code: " + connection.getResponseCode());
      return false;
    }
  }
 catch (  IOException e) {
    Log.e(TAG,e.toString());
    return false;
  }
  return true;
}
 

Example 108

From project SMSSync, under directory /smssync/src/org/addhen/smssync/net/.

Source file: MainHttpClient.java

  16 
vote

public MainHttpClient(String url){
  this.url=url;
  httpParameters=new BasicHttpParams();
  httpParameters.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS,1);
  httpParameters.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE,new ConnPerRouteBean(1));
  httpParameters.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE,false);
  HttpProtocolParams.setVersion(httpParameters,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(httpParameters,"utf8");
  HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
  HttpConnectionParams.setSoTimeout(httpParameters,timeoutSocket);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  try {
    schemeRegistry.register(new Scheme("https",new TrustedSocketFactory(url,false),443));
  }
 catch (  KeyManagementException e) {
    e.printStackTrace();
  }
catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
  ThreadSafeClientConnManager manager=new ThreadSafeClientConnManager(httpParameters,schemeRegistry);
  httpclient=new DefaultHttpClient(manager,httpParameters);
}
 

Example 109

From project Speedometer, under directory /android/src/com/google/wireless/speed/speedometer/.

Source file: Checkin.java

  16 
vote

/** 
 * Return an appropriately-configured HTTP client.
 */
private HttpClient getNewHttpClient(){
  DefaultHttpClient client;
  try {
    KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null,null);
    SSLSocketFactory sf=new MySSLSocketFactory(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);
    HttpConnectionParams.setConnectionTimeout(params,POST_TIMEOUT_MILLISEC);
    HttpConnectionParams.setSoTimeout(params,POST_TIMEOUT_MILLISEC);
    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);
    client=new DefaultHttpClient(ccm,params);
  }
 catch (  Exception e) {
    Logger.w("Unable to create SSL HTTP client",e);
    client=new DefaultHttpClient();
  }
  CookieStore store=new BasicCookieStore();
  store.addCookie(authCookie);
  client.setCookieStore(store);
  return client;
}
 

Example 110

From project SqueezeControl, under directory /src/com/squeezecontrol/image/.

Source file: HttpFetchingImageStore.java

  16 
vote

public HttpFetchingImageStore(String baseUrl,String username,String password){
  this.baseUrl=baseUrl;
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setStaleCheckingEnabled(params,false);
  HttpConnectionParams.setConnectionTimeout(params,20 * 1000);
  HttpConnectionParams.setSoTimeout(params,20 * 1000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager mgr=new ThreadSafeClientConnManager(params,schemeRegistry);
  mClient=new DefaultHttpClient(mgr,params);
  if (username != null && !"".equals(username)) {
    Credentials defaultcreds=new UsernamePasswordCredentials("dag","test");
    mClient.getCredentialsProvider().setCredentials(AuthScope.ANY,defaultcreds);
  }
}
 

Example 111

From project maven-wagon, under directory /wagon-providers/wagon-http-shared4/src/main/java/org/apache/maven/wagon/shared/http4/.

Source file: HttpMethodConfiguration.java

  15 
vote

public HttpParams asMethodParams(HttpParams defaults){
  if (!hasParams()) {
    return null;
  }
  DefaultedHttpParams p=new DefaultedHttpParams(new BasicHttpParams(),defaults);
  fillParams(p);
  return p;
}