android HttpClient,DefaultHttpClient,AbstractHttpClient之间关系
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了android HttpClient,DefaultHttpClient,AbstractHttpClient之间关系,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含38208字,纯文字阅读大概需要55分钟。
内容图文
HttpClient是一个接口,定义了连接和访问规范。
/* * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/client/HttpClient.java $ * $Revision: 676020 $ * $Date: 2008-07-11 09:38:49 -0700 (Fri, 11 Jul 2008) $ * * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * < http://www.apache.org/ >. * */ package org.apache.http.client; import java.io.IOException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.ClientConnectionManager; /** * Interface for an HTTP client. * HTTP clients encapsulate a smorgasbord of objects required to * execute HTTP requests while handling cookies, authentication, * connection management, and other features. * Thread safety of HTTP clients depends on the implementation * and configuration of the specific client. * * @author <a href="mailto:rolandw at apache.org">Roland Weber</a> * * * <!-- empty lines to avoid svn diff problems --> * @version $Revision: 676020 $ * * @since 4.0 */ public interface HttpClient { /** * Obtains the parameters for this client. * These parameters will become defaults for all requests being * executed with this client, and for the parameters of * dependent objects in this client. * * @return the default parameters */ HttpParams getParams() ; /** * Obtains the connection manager used by this client. * * @return the connection manager */ ClientConnectionManager getConnectionManager() ; /** * Executes a request using the default context. * * @param request the request to execute * * @return the response to the request. This is always a final response, * never an intermediate response with an 1xx status code. * Whether redirects or authentication challenges will be returned * or handled automatically depends on the implementation and * configuration of this client. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException ; /** * Executes a request using the given context. * The route to the target will be determined by the HTTP client. * * @param request the request to execute * @param context the context to use for the execution, or * <code>null</code> to use the default context * * @return the response to the request. This is always a final response, * never an intermediate response with an 1xx status code. * Whether redirects or authentication challenges will be returned * or handled automatically depends on the implementation and * configuration of this client. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException ; /** * Executes a request to the target using the default context. * * @param target the target host for the request. * Implementations may accept <code>null</code> * if they can still determine a route, for example * to a default target or by inspecting the request. * @param request the request to execute * * @return the response to the request. This is always a final response, * never an intermediate response with an 1xx status code. * Whether redirects or authentication challenges will be returned * or handled automatically depends on the implementation and * configuration of this client. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ HttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException ; /** * Executes a request to the target using the given context. * * @param target the target host for the request. * Implementations may accept <code>null</code> * if they can still determine a route, for example * to a default target or by inspecting the request. * @param request the request to execute * @param context the context to use for the execution, or * <code>null</code> to use the default context * * @return the response to the request. This is always a final response, * never an intermediate response with an 1xx status code. * Whether redirects or authentication challenges will be returned * or handled automatically depends on the implementation and * configuration of this client. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException ; /** * Executes a request using the default context and processes the * response using the given response handler. * * @param request the request to execute * @param responseHandler the response handler * * @return the response object as generated by the response handler. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ <T> T execute( HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException ; /** * Executes a request using the given context and processes the * response using the given response handler. * * @param request the request to execute * @param responseHandler the response handler * * @return the response object as generated by the response handler. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ <T> T execute( HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException, ClientProtocolException ; /** * Executes a request to the target using the default context and * processes the response using the given response handler. * * @param target the target host for the request. * Implementations may accept <code>null</code> * if they can still determine a route, for example * to a default target or by inspecting the request. * @param request the request to execute * @param responseHandler the response handler * * @return the response object as generated by the response handler. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ <T> T execute( HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException ; /** * Executes a request to the target using the given context and * processes the response using the given response handler. * * @param target the target host for the request. * Implementations may accept <code>null</code> * if they can still determine a route, for example * to a default target or by inspecting the request. * @param request the request to execute * @param responseHandler the response handler * @param context the context to use for the execution, or * <code>null</code> to use the default context * * @return the response object as generated by the response handler. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error */ <T> T execute( HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException, ClientProtocolException ; } // interface HttpClient
AbstractHttpClient 是一个实现了HttpClient接口的抽象类。
/* * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/impl/client/AbstractHttpClient.java $ * $Revision: 677250 $ * $Date: 2008-07-16 04:45:47 -0700 (Wed, 16 Jul 2008) $ * * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * < http://www.apache.org/ >. * */ package org.apache.http.impl.client; import java.io.IOException; import java.net.URI; import java.lang.reflect.UndeclaredThrowableException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpEntity; import org.apache.http.auth.AuthSchemeRegistry; import org.apache.http.client.AuthenticationHandler; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.RequestDirector; import org.apache.http.client.ResponseHandler; import org.apache.http.client.CookieStore; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.RedirectHandler; import org.apache.http.client.UserTokenHandler; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.cookie.CookieSpecRegistry; import org.apache.http.params.HttpParams; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.DefaultedHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpRequestExecutor; /** * Convenience base class for HTTP client implementations. * * @author <a href="mailto:rolandw at apache.org">Roland Weber</a> * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a> * * <!-- empty lines to avoid svn diff problems --> * @version $Revision: 677250 $ * * @since 4.0 */ public abstract class AbstractHttpClient implements HttpClient { privatefinal Log log = LogFactory.getLog(getClass()); /** The parameters. */private HttpParams defaultParams; /** The request executor. */private HttpRequestExecutor requestExec; /** The connection manager. */private ClientConnectionManager connManager; /** The connection re-use strategy. */private ConnectionReuseStrategy reuseStrategy; /** The connection keep-alive strategy. */private ConnectionKeepAliveStrategy keepAliveStrategy; /** The cookie spec registry. */private CookieSpecRegistry supportedCookieSpecs; /** The authentication scheme registry. */private AuthSchemeRegistry supportedAuthSchemes; /** The HTTP processor. */private BasicHttpProcessor httpProcessor; /** The request retry handler. */private HttpRequestRetryHandler retryHandler; /** The redirect handler. */private RedirectHandler redirectHandler; /** The target authentication handler. */private AuthenticationHandler targetAuthHandler; /** The proxy authentication handler. */private AuthenticationHandler proxyAuthHandler; /** The cookie store. */private CookieStore cookieStore; /** The credentials provider. */private CredentialsProvider credsProvider; /** The route planner. */private HttpRoutePlanner routePlanner; /** The user token handler. */private UserTokenHandler userTokenHandler; /** * Creates a new HTTP client. * * @param conman the connection manager * @param params the parameters */protected AbstractHttpClient( final ClientConnectionManager conman, final HttpParams params) { defaultParams = params; connManager = conman; } // constructorprotectedabstract HttpParams createHttpParams(); protectedabstract HttpContext createHttpContext(); protectedabstract HttpRequestExecutor createRequestExecutor(); protectedabstract ClientConnectionManager createClientConnectionManager(); protectedabstract AuthSchemeRegistry createAuthSchemeRegistry(); protectedabstract CookieSpecRegistry createCookieSpecRegistry(); protectedabstract ConnectionReuseStrategy createConnectionReuseStrategy(); protectedabstract ConnectionKeepAliveStrategy createConnectionKeepAliveStrategy(); protectedabstract BasicHttpProcessor createHttpProcessor(); protectedabstract HttpRequestRetryHandler createHttpRequestRetryHandler(); protectedabstract RedirectHandler createRedirectHandler(); protectedabstract AuthenticationHandler createTargetAuthenticationHandler(); protectedabstract AuthenticationHandler createProxyAuthenticationHandler(); protectedabstract CookieStore createCookieStore(); protectedabstract CredentialsProvider createCredentialsProvider(); protectedabstract HttpRoutePlanner createHttpRoutePlanner(); protectedabstract UserTokenHandler createUserTokenHandler(); // non-javadoc, see interface HttpClientpublicsynchronizedfinal HttpParams getParams() { if (defaultParams == null) { defaultParams = createHttpParams(); } return defaultParams; } /** * Replaces the parameters. * The implementation here does not update parameters of dependent objects. * * @param params the new default parameters */publicsynchronizedvoid setParams(HttpParams params) { defaultParams = params; } publicsynchronizedfinal ClientConnectionManager getConnectionManager() { if (connManager == null) { connManager = createClientConnectionManager(); } return connManager; } publicsynchronizedfinal HttpRequestExecutor getRequestExecutor() { if (requestExec == null) { requestExec = createRequestExecutor(); } return requestExec; } publicsynchronizedfinal AuthSchemeRegistry getAuthSchemes() { if (supportedAuthSchemes == null) { supportedAuthSchemes = createAuthSchemeRegistry(); } return supportedAuthSchemes; } publicsynchronizedvoid setAuthSchemes(final AuthSchemeRegistry authSchemeRegistry) { supportedAuthSchemes = authSchemeRegistry; } publicsynchronizedfinal CookieSpecRegistry getCookieSpecs() { if (supportedCookieSpecs == null) { supportedCookieSpecs = createCookieSpecRegistry(); } return supportedCookieSpecs; } publicsynchronizedvoid setCookieSpecs(final CookieSpecRegistry cookieSpecRegistry) { supportedCookieSpecs = cookieSpecRegistry; } publicsynchronizedfinal ConnectionReuseStrategy getConnectionReuseStrategy() { if (reuseStrategy == null) { reuseStrategy = createConnectionReuseStrategy(); } return reuseStrategy; } publicsynchronizedvoid setReuseStrategy(final ConnectionReuseStrategy reuseStrategy) { this.reuseStrategy = reuseStrategy; } publicsynchronizedfinal ConnectionKeepAliveStrategy getConnectionKeepAliveStrategy() { if (keepAliveStrategy == null) { keepAliveStrategy = createConnectionKeepAliveStrategy(); } return keepAliveStrategy; } publicsynchronizedvoid setKeepAliveStrategy(final ConnectionKeepAliveStrategy keepAliveStrategy) { this.keepAliveStrategy = keepAliveStrategy; } publicsynchronizedfinal HttpRequestRetryHandler getHttpRequestRetryHandler() { if (retryHandler == null) { retryHandler = createHttpRequestRetryHandler(); } return retryHandler; } publicsynchronizedvoid setHttpRequestRetryHandler(final HttpRequestRetryHandler retryHandler) { this.retryHandler = retryHandler; } publicsynchronizedfinal RedirectHandler getRedirectHandler() { if (redirectHandler == null) { redirectHandler = createRedirectHandler(); } return redirectHandler; } publicsynchronizedvoid setRedirectHandler(final RedirectHandler redirectHandler) { this.redirectHandler = redirectHandler; } publicsynchronizedfinal AuthenticationHandler getTargetAuthenticationHandler() { if (targetAuthHandler == null) { targetAuthHandler = createTargetAuthenticationHandler(); } return targetAuthHandler; } publicsynchronizedvoid setTargetAuthenticationHandler( final AuthenticationHandler targetAuthHandler) { this.targetAuthHandler = targetAuthHandler; } publicsynchronizedfinal AuthenticationHandler getProxyAuthenticationHandler() { if (proxyAuthHandler == null) { proxyAuthHandler = createProxyAuthenticationHandler(); } return proxyAuthHandler; } publicsynchronizedvoid setProxyAuthenticationHandler( final AuthenticationHandler proxyAuthHandler) { this.proxyAuthHandler = proxyAuthHandler; } publicsynchronizedfinal CookieStore getCookieStore() { if (cookieStore == null) { cookieStore = createCookieStore(); } return cookieStore; } publicsynchronizedvoid setCookieStore(final CookieStore cookieStore) { this.cookieStore = cookieStore; } publicsynchronizedfinal CredentialsProvider getCredentialsProvider() { if (credsProvider == null) { credsProvider = createCredentialsProvider(); } return credsProvider; } publicsynchronizedvoid setCredentialsProvider(final CredentialsProvider credsProvider) { this.credsProvider = credsProvider; } publicsynchronizedfinal HttpRoutePlanner getRoutePlanner() { if (this.routePlanner == null) { this.routePlanner = createHttpRoutePlanner(); } returnthis.routePlanner; } publicsynchronizedvoid setRoutePlanner(final HttpRoutePlanner routePlanner) { this.routePlanner = routePlanner; } publicsynchronizedfinal UserTokenHandler getUserTokenHandler() { if (this.userTokenHandler == null) { this.userTokenHandler = createUserTokenHandler(); } returnthis.userTokenHandler; } publicsynchronizedvoid setUserTokenHandler(final UserTokenHandler userTokenHandler) { this.userTokenHandler = userTokenHandler; } protectedsynchronizedfinal BasicHttpProcessor getHttpProcessor() { if (httpProcessor == null) { httpProcessor = createHttpProcessor(); } return httpProcessor; } publicsynchronizedvoid addResponseInterceptor(final HttpResponseInterceptor itcp) { getHttpProcessor().addInterceptor(itcp); } publicsynchronizedvoid addResponseInterceptor(final HttpResponseInterceptor itcp, int index) { getHttpProcessor().addInterceptor(itcp, index); } publicsynchronized HttpResponseInterceptor getResponseInterceptor(int index) { return getHttpProcessor().getResponseInterceptor(index); } publicsynchronizedint getResponseInterceptorCount() { return getHttpProcessor().getResponseInterceptorCount(); } publicsynchronizedvoid clearResponseInterceptors() { getHttpProcessor().clearResponseInterceptors(); } publicvoid removeResponseInterceptorByClass(Class<? extends HttpResponseInterceptor> clazz) { getHttpProcessor().removeResponseInterceptorByClass(clazz); } publicsynchronizedvoid addRequestInterceptor(final HttpRequestInterceptor itcp) { getHttpProcessor().addInterceptor(itcp); } publicsynchronizedvoid addRequestInterceptor(final HttpRequestInterceptor itcp, int index) { getHttpProcessor().addInterceptor(itcp, index); } publicsynchronized HttpRequestInterceptor getRequestInterceptor(int index) { return getHttpProcessor().getRequestInterceptor(index); } publicsynchronizedint getRequestInterceptorCount() { return getHttpProcessor().getRequestInterceptorCount(); } publicsynchronizedvoid clearRequestInterceptors() { getHttpProcessor().clearRequestInterceptors(); } publicvoid removeRequestInterceptorByClass(Class<? extends HttpRequestInterceptor> clazz) { getHttpProcessor().removeRequestInterceptorByClass(clazz); } // non-javadoc, see interface HttpClientpublicfinal HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException { return execute(request, (HttpContext) null); } /** * Maps to {@link HttpClient#execute(HttpHost,HttpRequest,HttpContext) * execute(target, request, context)}. * The target is determined from the URI of the request. * * @param request the request to execute * @param context the request-specific execution context, * or <code>null</code> to use a default context */publicfinal HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException { if (request == null) { thrownew IllegalArgumentException ("Request must not be null."); } return execute(determineTarget(request), request, context); } private HttpHost determineTarget(HttpUriRequest request) { // A null target may be acceptable if there is a default target. // Otherwise, the null target is detected in the director. HttpHost target = null; URI requestURI = request.getURI(); if (requestURI.isAbsolute()) { target = new HttpHost( requestURI.getHost(), requestURI.getPort(), requestURI.getScheme()); } return target; } // non-javadoc, see interface HttpClientpublicfinal HttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException { return execute(target, request, (HttpContext) null); } // non-javadoc, see interface HttpClientpublicfinal HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException { if (request == null) { thrownew IllegalArgumentException ("Request must not be null."); } // a null target may be acceptable, this depends on the route planner // a null context is acceptable, default context created below HttpContext execContext = null; RequestDirector director = null; // Initialize the request execution context making copies of // all shared objects that are potentially threading unsafe.synchronized (this) { HttpContext defaultContext = createHttpContext(); if (context == null) { execContext = defaultContext; } else { execContext = new DefaultedHttpContext(context, defaultContext); } // Create a director for this request director = createClientRequestDirector( getRequestExecutor(), getConnectionManager(), getConnectionReuseStrategy(), getConnectionKeepAliveStrategy(), getRoutePlanner(), getHttpProcessor().copy(), getHttpRequestRetryHandler(), getRedirectHandler(), getTargetAuthenticationHandler(), getProxyAuthenticationHandler(), getUserTokenHandler(), determineParams(request)); } try { return director.execute(target, request, execContext); } catch(HttpException httpException) { thrownew ClientProtocolException(httpException); } } // executeprotected RequestDirector createClientRequestDirector( 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 stateHandler, final HttpParams params) { returnnew DefaultRequestDirector( requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectHandler, targetAuthHandler, proxyAuthHandler, stateHandler, params); } /** * Obtains parameters for executing a request. * The default implementation in this class creates a new * {@link ClientParamsStack} from the request parameters * and the client parameters. * <br/> * This method is called by the default implementation of * {@link #execute(HttpHost,HttpRequest,HttpContext)} * to obtain the parameters for the * {@link DefaultRequestDirector}. * * @param req the request that will be executed * * @return the parameters to use */protected HttpParams determineParams(HttpRequest req) { returnnew ClientParamsStack (null, getParams(), req.getParams(), null); } // non-javadoc, see interface HttpClientpublic <T> T execute( final HttpUriRequest request, final ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException { return execute(request, responseHandler, null); } // non-javadoc, see interface HttpClientpublic <T> T execute( final HttpUriRequest request, final ResponseHandler<? extends T> responseHandler, final HttpContext context) throws IOException, ClientProtocolException { HttpHost target = determineTarget(request); return execute(target, request, responseHandler, context); } // non-javadoc, see interface HttpClientpublic <T> T execute( final HttpHost target, final HttpRequest request, final ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException { return execute(target, request, responseHandler, null); } // non-javadoc, see interface HttpClientpublic <T> T execute( final HttpHost target, final HttpRequest request, final ResponseHandler<? extends T> responseHandler, final HttpContext context) throws IOException, ClientProtocolException { if (responseHandler == null) { thrownew IllegalArgumentException ("Response handler must not be null."); } HttpResponse response = execute(target, request, context); T result; try { result = responseHandler.handleResponse(response); } catch (Throwable t) { HttpEntity entity = response.getEntity(); if (entity != null) { try { entity.consumeContent(); } catch (Throwable t2) { // Log this exception. The original exception is more // important and will be thrown to the caller.this.log.warn("Error consuming content after an exception.", t2); } } if (t instanceof Error) { throw (Error) t; } if (t instanceof RuntimeException) { throw (RuntimeException) t; } if (t instanceof IOException) { throw (IOException) t; } thrownew UndeclaredThrowableException(t); } // Handling the response was successful. Ensure that the content has // been fully consumed. HttpEntity entity = response.getEntity(); if (entity != null) { // Let this exception go to the caller. entity.consumeContent(); } return result; } } // class AbstractHttpClient
DefaultHttpClient是一个继承AbstractHttpClient的类。
/* * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/impl/client/DefaultHttpClient.java $ * $Revision: 677250 $ * $Date: 2008-07-16 04:45:47 -0700 (Wed, 16 Jul 2008) $ * * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * < http://www.apache.org/ >. * */ package org.apache.http.impl.client; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpVersion; import org.apache.http.auth.AuthSchemeRegistry; import org.apache.http.client.AuthenticationHandler; import org.apache.http.client.CookieStore; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.RedirectHandler; import org.apache.http.client.UserTokenHandler; import org.apache.http.client.params.AuthPolicy; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.protocol.ClientContext; import org.apache.http.client.protocol.RequestAddCookies; import org.apache.http.client.protocol.RequestDefaultHeaders; import org.apache.http.client.protocol.RequestProxyAuthentication; import org.apache.http.client.protocol.RequestTargetAuthentication; import org.apache.http.client.protocol.ResponseProcessCookies; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionManagerFactory; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.cookie.CookieSpecRegistry; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.auth.BasicSchemeFactory; import org.apache.http.impl.auth.DigestSchemeFactory; import org.apache.http.impl.conn.DefaultHttpRoutePlanner; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.impl.cookie.BestMatchSpecFactory; import org.apache.http.impl.cookie.BrowserCompatSpecFactory; import org.apache.http.impl.cookie.NetscapeDraftSpecFactory; import org.apache.http.impl.cookie.RFC2109SpecFactory; import org.apache.http.impl.cookie.RFC2965SpecFactory; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.util.VersionInfo; /** * Default implementation of an HTTP client. * <br/> * This class replaces <code>HttpClient</code> in HttpClient 3. * * @author <a href="mailto:rolandw at apache.org">Roland Weber</a> * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a> * * <!-- empty lines to avoid svn diff problems --> * @version $Revision: 677250 $ * * @since 4.0 */ public class DefaultHttpClient extends AbstractHttpClient { /** * Creates a new HTTP client from parameters and a connection manager. * * @param params the parameters * @param conman the connection manager */public DefaultHttpClient( final ClientConnectionManager conman, final HttpParams params) { super(conman, params); } public DefaultHttpClient(final HttpParams params) { super(null, params); } public DefaultHttpClient() { super(null, null); } @Override protected HttpParams createHttpParams() { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET); /* * Android note: Send each request body without first asking the server * whether it will be accepted. Asking first slows down the common case * and results in "417 expectation failed" errors when a HTTP/1.0 server * is behind a proxy. http://b/2471595*/ HttpProtocolParams.setUseExpectContinue(params, false); // android-changed // determine the release version from packaged version infofinal 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; } @Override protected HttpRequestExecutor createRequestExecutor() { returnnew HttpRequestExecutor(); } @Override protected ClientConnectionManager createClientConnectionManager() { SchemeRegistry registry = new SchemeRegistry(); registry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register( new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager connManager = null; HttpParams params = getParams(); ClientConnectionManagerFactory factory = null; // Try first getting the factory directly as an object. factory = (ClientConnectionManagerFactory) params .getParameter(ClientPNames.CONNECTION_MANAGER_FACTORY); if (factory == null) { // then try getting its class name. String className = (String) params.getParameter( ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME); if (className != null) { try { Class<?> clazz = Class.forName(className); factory = (ClientConnectionManagerFactory) clazz.newInstance(); } catch (ClassNotFoundException ex) { thrownew IllegalStateException("Invalid class name: " + className); } catch (IllegalAccessException ex) { thrownew IllegalAccessError(ex.getMessage()); } catch (InstantiationException ex) { thrownew InstantiationError(ex.getMessage()); } } } if(factory != null) { connManager = factory.newInstance(params, registry); } else { connManager = new SingleClientConnManager(getParams(), registry); } return connManager; } @Override protected HttpContext createHttpContext() { HttpContext context = new BasicHttpContext(); context.setAttribute( ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes()); context.setAttribute( ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs()); context.setAttribute( ClientContext.COOKIE_STORE, getCookieStore()); context.setAttribute( ClientContext.CREDS_PROVIDER, getCredentialsProvider()); return context; } @Override protected ConnectionReuseStrategy createConnectionReuseStrategy() { returnnew DefaultConnectionReuseStrategy(); } @Override protected ConnectionKeepAliveStrategy createConnectionKeepAliveStrategy() { returnnew DefaultConnectionKeepAliveStrategy(); } @Override protected AuthSchemeRegistry createAuthSchemeRegistry() { AuthSchemeRegistry registry = new AuthSchemeRegistry(); registry.register( AuthPolicy.BASIC, new BasicSchemeFactory()); registry.register( AuthPolicy.DIGEST, new DigestSchemeFactory()); return registry; } @Override protected CookieSpecRegistry createCookieSpecRegistry() { CookieSpecRegistry registry = new CookieSpecRegistry(); registry.register( CookiePolicy.BEST_MATCH, new BestMatchSpecFactory()); registry.register( CookiePolicy.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()); registry.register( CookiePolicy.NETSCAPE, new NetscapeDraftSpecFactory()); registry.register( CookiePolicy.RFC_2109, new RFC2109SpecFactory()); registry.register( CookiePolicy.RFC_2965, new RFC2965SpecFactory()); return registry; } @Override protected BasicHttpProcessor createHttpProcessor() { BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new RequestDefaultHeaders()); // Required protocol interceptors httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); // Recommended protocol interceptors httpproc.addInterceptor(new RequestConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); // HTTP state management interceptors httpproc.addInterceptor(new RequestAddCookies()); httpproc.addInterceptor(new ResponseProcessCookies()); // HTTP authentication interceptors httpproc.addInterceptor(new RequestTargetAuthentication()); httpproc.addInterceptor(new RequestProxyAuthentication()); return httpproc; } @Override protected HttpRequestRetryHandler createHttpRequestRetryHandler() { returnnew DefaultHttpRequestRetryHandler(); } @Override protected RedirectHandler createRedirectHandler() { returnnew DefaultRedirectHandler(); } @Override protected AuthenticationHandler createTargetAuthenticationHandler() { returnnew DefaultTargetAuthenticationHandler(); } @Override protected AuthenticationHandler createProxyAuthenticationHandler() { returnnew DefaultProxyAuthenticationHandler(); } @Override protected CookieStore createCookieStore() { returnnew BasicCookieStore(); } @Override protected CredentialsProvider createCredentialsProvider() { returnnew BasicCredentialsProvider(); } @Override protected HttpRoutePlanner createHttpRoutePlanner() { returnnew DefaultHttpRoutePlanner (getConnectionManager().getSchemeRegistry()); } @Override protected UserTokenHandler createUserTokenHandler() { returnnew DefaultUserTokenHandler(); } } // class DefaultHttpClient
原文:http://www.cnblogs.com/answer1022/p/3570847.html
内容总结
以上是互联网集市为您收集整理的android HttpClient,DefaultHttpClient,AbstractHttpClient之间关系全部内容,希望文章能够帮你解决android HttpClient,DefaultHttpClient,AbstractHttpClient之间关系所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。