public static HttpClient get() { HttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, 3000); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(30)); ConnManagerParams.setMaxTotalConnections(httpParams, 30); HttpClientParams.setRedirecting(httpParams, true); HttpProtocolParams.setUseExpectContinue(httpParams, true); HttpConnectionParams.setStaleCheckingEnabled(httpParams, false); HttpConnectionParams.setSoTimeout(httpParams, 2000); HttpConnectionParams.setConnectionTimeout(httpParams, 2000); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, 8192); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme(IDataSource.SCHEME_HTTP_TAG, PlainSocketFactory.getSocketFactory(), 80)); try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); schemeRegistry.register(new Scheme(IDataSource.SCHEME_HTTPS_TAG, sf, 443)); } catch (Exception ex) { ex.printStackTrace(); } return new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams); }
private static HttpClient getNewHttpClient() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 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(); } }
public static b a(String str) { HttpParams basicHttpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(basicHttpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUseExpectContinue(basicHttpParams, false); HttpConnectionParams.setStaleCheckingEnabled(basicHttpParams, false); HttpConnectionParams.setConnectionTimeout(basicHttpParams, 20000); HttpConnectionParams.setSoTimeout(basicHttpParams, 30000); HttpConnectionParams.setSocketBufferSize(basicHttpParams, 8192); HttpClientParams.setRedirecting(basicHttpParams, true); HttpClientParams.setAuthenticating(basicHttpParams, false); HttpProtocolParams.setUserAgent(basicHttpParams, str); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme(com.alipay.sdk.cons.b.a, SSLCertificateSocketFactory.getHttpSocketFactory(30000, null), WebSocket.DEFAULT_WSS_PORT)); ClientConnectionManager threadSafeClientConnManager = new ThreadSafeClientConnManager(basicHttpParams, schemeRegistry); ConnManagerParams.setTimeout(basicHttpParams, 60000); ConnManagerParams.setMaxConnectionsPerRoute(basicHttpParams, new ConnPerRouteBean(10)); ConnManagerParams.setMaxTotalConnections(basicHttpParams, 50); Security.setProperty("networkaddress.cache.ttl", "-1"); HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); return new b(threadSafeClientConnManager, basicHttpParams); }
public void update(Socket sock, HttpHost target, boolean secure, HttpParams params) throws IOException { assertOpen(); if (target == null) { throw new IllegalArgumentException ("Target host must not be null."); } if (params == null) { throw new IllegalArgumentException ("Parameters must not be null."); } if (sock != null) { this.socket = sock; bind(sock, params); } targetHost = target; connSecure = secure; }
public DefaultHttpClient getHttpClientInstance() { if (this.httpClient != null) { return this.httpClient; } HttpParams params = new BasicHttpParams(); params.setParameter("http.connection.timeout", CONNECTION_TIMEOUT); params.setParameter("http.socket.timeout", SOCKET_TIMEOUT); params.setParameter("http.protocol.version", HttpVersion.HTTP_1_1); params.setParameter("http.useragent", "Apache-HttpClient/Android"); params.setParameter("http.connection.stalecheck", Boolean.valueOf(false)); this.httpClient = new DefaultHttpClient(params); this.httpClient.addRequestInterceptor(new GzipHttpRequestInterceptor()); this.httpClient.addResponseInterceptor(new GzipHttpResponseInterceptor()); this.httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); return this.httpClient; }
public synchronized static DefaultHttpClient getHttpClient() { try { HttpParams params = new BasicHttpParams(); // 设置一些基本参数 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // 超时设置 // 从连接池中取连接的超时时间 ConnManagerParams.setTimeout(params, 10000); // 连接超时 HttpConnectionParams.setConnectionTimeout(params, 10000); // 请求超时 HttpConnectionParams.setSoTimeout(params, 30000); SchemeRegistry registry = new SchemeRegistry(); Scheme sch1 = new Scheme("http", PlainSocketFactory .getSocketFactory(), 80); registry.register(sch1); // 使用线程安全的连接管理来创建HttpClient ClientConnectionManager conMgr = new ThreadSafeClientConnManager( params, registry); mHttpClient = new DefaultHttpClient(conMgr, params); } catch (Exception e) { e.printStackTrace(); } return mHttpClient; }
@Override protected SessionInputBuffer createSessionInputBuffer( final Socket socket, int buffersize, final HttpParams params) throws IOException { if (buffersize == -1) { buffersize = 8192; } SessionInputBuffer inbuffer = super.createSessionInputBuffer( socket, buffersize, params); if (wireLog.isDebugEnabled()) { inbuffer = new LoggingSessionInputBuffer( inbuffer, new Wire(wireLog), HttpProtocolParams.getHttpElementCharset(params)); } return inbuffer; }
public CookieSpec newInstance(final HttpParams params) { if (params != null) { String[] patterns = null; Collection<?> param = (Collection<?>) params.getParameter( CookieSpecPNames.DATE_PATTERNS); if (param != null) { patterns = new String[param.size()]; patterns = param.toArray(patterns); } boolean singleHeader = params.getBooleanParameter( CookieSpecPNames.SINGLE_COOKIE_HEADER, false); return new BestMatchSpec(patterns, singleHeader); } else { return new BestMatchSpec(); } }
/** * Tracks tunnelling of the connection to a chained proxy. * The tunnel has to be established outside by sending a CONNECT * request to the previous proxy. * * @param next the proxy to which the tunnel was established. * See {@link org.apache.http.conn.ManagedClientConnection#tunnelProxy * ManagedClientConnection.tunnelProxy} * for details. * @param secure <code>true</code> if the tunnel should be * considered secure, <code>false</code> otherwise * @param params the parameters for tunnelling the connection * * @throws IOException in case of a problem */ public void tunnelProxy(HttpHost next, boolean secure, HttpParams params) throws IOException { if (next == null) { throw new IllegalArgumentException ("Next proxy must not be null."); } if (params == null) { throw new IllegalArgumentException ("Parameters must not be null."); } //@@@ check for proxy in planned route? if ((this.tracker == null) || !this.tracker.isConnected()) { throw new IllegalStateException("Connection not open."); } this.connection.update(null, next, secure, params); this.tracker.tunnelProxy(next, secure); }
/** * Initializes this connection object with {@link SessionInputBuffer} and * {@link SessionOutputBuffer} instances to be used for sending and * receiving data. These session buffers can be bound to any arbitrary * physical output medium. * <p> * This method will invoke {@link #createHttpResponseFactory()}, * {@link #createRequestWriter(SessionOutputBuffer, HttpParams)} * and {@link #createResponseParser(SessionInputBuffer, HttpResponseFactory, HttpParams)} * methods to initialize HTTP request writer and response parser for this * connection. * * @param inbuffer the session input buffer. * @param outbuffer the session output buffer. * @param params HTTP parameters. */ protected void init( final SessionInputBuffer inbuffer, final SessionOutputBuffer outbuffer, final HttpParams params) { if (inbuffer == null) { throw new IllegalArgumentException("Input session buffer may not be null"); } if (outbuffer == null) { throw new IllegalArgumentException("Output session buffer may not be null"); } this.inbuffer = inbuffer; this.outbuffer = outbuffer; if (inbuffer instanceof EofSensor) { this.eofSensor = (EofSensor) inbuffer; } this.responseParser = createResponseParser( inbuffer, createHttpResponseFactory(), params); this.requestWriter = createRequestWriter( outbuffer, params); this.metrics = createConnectionMetrics( inbuffer.getMetrics(), outbuffer.getMetrics()); }
@Deprecated public DefaultRequestDirector( final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectHandler redirectHandler, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler userTokenHandler, final HttpParams params) { this(LogFactory.getLog(DefaultRequestDirector.class), requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, new DefaultRedirectStrategyAdaptor(redirectHandler), new AuthenticationStrategyAdaptor(targetAuthHandler), new AuthenticationStrategyAdaptor(proxyAuthHandler), userTokenHandler, params); }
@Deprecated public DefaultRequestDirector( final Log log, final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectStrategy redirectStrategy, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler userTokenHandler, final HttpParams params) { this(LogFactory.getLog(DefaultRequestDirector.class), requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectStrategy, new AuthenticationStrategyAdaptor(targetAuthHandler), new AuthenticationStrategyAdaptor(proxyAuthHandler), userTokenHandler, params); }
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); HttpParams httpParams = new BasicHttpParams(); when(mockHttpClientFactory.create()).thenReturn(mockHttpClient); when(mockHttpClient.getParams()).thenReturn(httpParams); when(mockHttpClient.getConnectionManager()).thenReturn(mockClientConnectionManager); when(mockClientConnectionManager.getSchemeRegistry()).thenReturn(mockSchemeRegistry); }
/** * Sets maximum limit of parallel connections * * @param maxConnections maximum parallel connections, must be at least 1 */ public void setMaxConnections(int maxConnections) { if (maxConnections < 1) maxConnections = DEFAULT_MAX_CONNECTIONS; this.maxConnections = maxConnections; final HttpParams httpParams = this.httpClient.getParams(); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(this.maxConnections)); }
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) { try { SSLSocketFactory sf = new MySSLSocketFactory(keyStore); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme(b.a, sf, WebSocket.DEFAULT_WSS_PORT)); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); return new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params); } catch (Exception e) { return new DefaultHttpClient(); } }
private ak(Context context) { try { dk = context.getApplicationContext(); this.cv = System.currentTimeMillis() / 1000; this.dh = new f(); if (c.k()) { try { Logger.getLogger("org.apache.http.wire").setLevel(Level.FINER); Logger.getLogger("org.apache.http.headers").setLevel(Level.FINER); System.setProperty("org.apache.commons.logging.Log", "org.apache.commons" + ".logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); System.setProperty("org.apache.commons.logging.simplelog.log.httpclient" + ".wire", BuildConfig.BUILD_TYPE); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache" + ".http", BuildConfig.BUILD_TYPE); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http" + ".headers", BuildConfig.BUILD_TYPE); } catch (Throwable th) { } } HttpParams basicHttpParams = new BasicHttpParams(); HttpConnectionParams.setStaleCheckingEnabled(basicHttpParams, false); HttpConnectionParams.setConnectionTimeout(basicHttpParams, 10000); HttpConnectionParams.setSoTimeout(basicHttpParams, 10000); this.dg = new DefaultHttpClient(basicHttpParams); this.dg.setKeepAliveStrategy(new al(this)); } catch (Throwable th2) { cx.b(th2); } }
/** * Set the connection and socket timeout. By default, 10 seconds. * * @param timeout the connect/socket timeout in milliseconds, at least 1 second */ public void setTimeout(int timeout) { if (timeout < 1000) timeout = DEFAULT_SOCKET_TIMEOUT; this.timeout = timeout; final HttpParams httpParams = this.httpClient.getParams(); ConnManagerParams.setTimeout(httpParams, this.timeout); HttpConnectionParams.setSoTimeout(httpParams, this.timeout); HttpConnectionParams.setConnectionTimeout(httpParams, this.timeout); }
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders); addHeaders(httpRequest, additionalHeaders); addHeaders(httpRequest, request.getHeaders()); onPrepareRequest(httpRequest); HttpParams httpParams = httpRequest.getParams(); int timeoutMs = request.getTimeoutMs(); // TODO: Reevaluate this connection timeout based on more wide-scale // data collection and possibly different for wifi vs. 3G. HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, timeoutMs); return mClient.execute(httpRequest); }
/** * Execute Http request and response code * @param request - HTTP Request * @param expectedCode - expected response code * @return - response in JSONObject */ public JSON query(HttpRequestBase request, int expectedCode) throws IOException { log.info("Requesting: " + request); addRequiredHeader(request); HttpParams requestParams = request.getParams(); requestParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT * 1000); requestParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT * 1000); synchronized (httpClient) { String response; try { HttpResponse result = httpClient.execute(request); int statusCode = result.getStatusLine().getStatusCode(); response = getResponseEntity(result); if (statusCode != expectedCode) { notifier.notifyAbout("Response with code " + statusCode + ": " + extractErrorMessage(response)); throw new IOException("API responded with wrong status code: " + statusCode); } else { log.debug("Response: " + response); } } finally { request.abort(); } if (response == null || response.isEmpty()) { return JSONNull.getInstance(); } else { return JSONSerializer.toJSON(response, new JsonConfig()); } } }
/** * Performs standard initializations on a newly created socket. * * @param sock the socket to prepare * @param context the context for the connection * @param params the parameters from which to prepare the socket * * @throws IOException in case of an IO problem */ protected void prepareSocket( final Socket sock, final HttpContext context, final HttpParams params) throws IOException { sock.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params)); sock.setSoTimeout(HttpConnectionParams.getSoTimeout(params)); int linger = HttpConnectionParams.getLinger(params); if (linger >= 0) { sock.setSoLinger(linger > 0, linger); } }
/** * Retrieves the current connection timeout, null if not set or if set to Integer.MIN_VALUE * * @return The current timeout */ protected Integer getIntClientParameter(final String parameter) { HttpParams params = httpClient.getParams(); int value = params.getIntParameter(parameter, Integer.MIN_VALUE); if (value != Integer.MIN_VALUE) { return value; } else { return null; } }
/** * Creates an instance of AbstractMessageWriter. * * @param buffer the session output buffer. * @param formatter the line formatter. * @param params HTTP parameters. */ public AbstractMessageWriter(final SessionOutputBuffer buffer, final LineFormatter formatter, final HttpParams params) { super(); if (buffer == null) { throw new IllegalArgumentException("Session input buffer may not be null"); } this.sessionBuffer = buffer; this.lineBuf = new CharArrayBuffer(128); this.lineFormatter = (formatter != null) ? formatter : BasicLineFormatter.DEFAULT; }
public Socket connectSocket( final Socket sock, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { return this.factory.connectSocket(sock, remoteAddress, localAddress, params); }
/** * Creates an instance of this class. * * @param buffer the session input buffer. * @param parser the line parser. * @param requestFactory the factory to use to create * {@link HttpRequest}s. * @param params HTTP parameters. */ public DefaultHttpRequestParser( final SessionInputBuffer buffer, final LineParser parser, final HttpRequestFactory requestFactory, final HttpParams params) { super(buffer, parser, params); if (requestFactory == null) { throw new IllegalArgumentException("Request factory may not be null"); } this.requestFactory = requestFactory; this.lineBuf = new CharArrayBuffer(128); }
/** * Sets the Proxy by it's hostname,port,username and password * * @param hostname the hostname (IP or DNS name) * @param port the port number. -1 indicates the scheme default port. * @param username the username * @param password the password */ public void setProxy(String hostname, int port, String username, String password) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(hostname, port), new UsernamePasswordCredentials(username, password)); final HttpHost proxy = new HttpHost(hostname, port); final HttpParams httpParams = this.httpClient.getParams(); httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); }
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders); addHeaders(httpRequest, additionalHeaders); addHeaders(httpRequest, request.getHeaders()); onPrepareRequest(httpRequest); HttpParams httpParams = httpRequest.getParams(); int timeoutMs = request.getTimeoutMs(); HttpConnectionParams.setConnectionTimeout(httpParams, BaseImageDownloader.DEFAULT_HTTP_CONNECT_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, timeoutMs); return this.mClient.execute(httpRequest); }
private static HttpClient getNewHttpClient() { 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(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 25000); 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); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 25000); HttpClient client = new DefaultHttpClient(ccm, params); // if (NetState.Mobile == NetStateManager.CUR_NETSTATE) { // // ?????????APN??? // HttpHost proxy = NetStateManager.getAPN(); // if (null != proxy) { // client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); // } // } return client; } catch (Exception e) { return new DefaultHttpClient(); } }
/** * Obtains the charset for encoding * {@link org.apache.http.auth.Credentials}.If not configured, * {@link HTTP#DEFAULT_PROTOCOL_CHARSET}is used instead. * * @return The charset */ public static String getCredentialCharset(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } String charset = (String) params.getParameter (AuthPNames.CREDENTIAL_CHARSET); if (charset == null) { charset = HTTP.DEF_PROTOCOL_CHARSET.name(); } return charset; }
public static void setAuthenticating(final HttpParams params, boolean value) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setBooleanParameter (ClientPNames.HANDLE_AUTHENTICATION, value); }
public BasicConnFactory(final SSLSocketFactory sslfactory, final HttpParams params) { super(); if (params == null) { throw new IllegalArgumentException("HTTP params may not be null"); } this.sslfactory = sslfactory; this.params = params; }
public void openCompleted(boolean secure, HttpParams params) throws IOException { assertNotOpen(); if (params == null) { throw new IllegalArgumentException ("Parameters must not be null."); } this.connSecure = secure; bind(this.socket, params); }
/** * Set the parameter {@code ClientPNames.CONN_MANAGER_TIMEOUT}. * * @since 4.2 */ public static void setConnectionManagerTimeout(final HttpParams params, long timeout) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, timeout); }
/** * Get the connectiion manager timeout value. * This is defined by the parameter {@code ClientPNames.CONN_MANAGER_TIMEOUT}. * Failing that it uses the parameter {@code CoreConnectionPNames.CONNECTION_TIMEOUT} * which defaults to 0 if not defined. * * @since 4.2 * @return the timeout value */ public static long getConnectionManagerTimeout(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } Long timeout = (Long) params.getParameter(ClientPNames.CONN_MANAGER_TIMEOUT); if (timeout != null) { return timeout.longValue(); } return HttpConnectionParams.getConnectionTimeout(params); }
/** * Obtains the {@link ConnRoutePNames#FORCED_ROUTE FORCED_ROUTE} * parameter value. * {@link #NO_ROUTE} will be mapped to <code>null</code>, * to allow unsetting in a hierarchy. * * @param params the parameters in which to look up * * @return the forced route set in the argument parameters, or * <code>null</code> if not set */ public static HttpRoute getForcedRoute(HttpParams params) { if (params == null) { throw new IllegalArgumentException("Parameters must not be null."); } HttpRoute route = (HttpRoute) params.getParameter(FORCED_ROUTE); if ((route != null) && NO_ROUTE.equals(route)) { // value is explicitly unset route = null; } return route; }