Don't need to block multiple thread access. Refactor and update a bit for an upcoming...
[zxing.git] / android / src / com / google / zxing / client / android / AndroidHttpClient.java
1 /*
2  * Copyright (C) 2008 ZXing authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.client.android;
18
19 import org.apache.http.HttpHost;
20 import org.apache.http.HttpRequest;
21 import org.apache.http.HttpRequestInterceptor;
22 import org.apache.http.HttpResponse;
23 import org.apache.http.client.HttpClient;
24 import org.apache.http.client.ResponseHandler;
25 import org.apache.http.client.methods.HttpUriRequest;
26 import org.apache.http.client.params.HttpClientParams;
27 import org.apache.http.client.protocol.ClientContext;
28 import org.apache.http.conn.ClientConnectionManager;
29 import org.apache.http.conn.scheme.PlainSocketFactory;
30 import org.apache.http.conn.scheme.Scheme;
31 import org.apache.http.conn.scheme.SchemeRegistry;
32 import org.apache.http.conn.ssl.SSLSocketFactory;
33 import org.apache.http.impl.client.DefaultHttpClient;
34 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
35 import org.apache.http.params.BasicHttpParams;
36 import org.apache.http.params.HttpConnectionParams;
37 import org.apache.http.params.HttpParams;
38 import org.apache.http.params.HttpProtocolParams;
39 import org.apache.http.protocol.BasicHttpContext;
40 import org.apache.http.protocol.HttpContext;
41
42 import java.io.IOException;
43
44 /**
45  * <p>Subclass of the Apache {@link DefaultHttpClient} that is configured with
46  * reasonable default settings and registered schemes for Android, and
47  * also lets the user add {@link HttpRequestInterceptor} classes.
48  * Don't create this directly, use the {@link #newInstance} factory method.</p>
49  * <p/>
50  * <p>This client processes cookies but does not retain them by default.
51  * To retain cookies, simply add a cookie store to the HttpContext:
52  * <pre>context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);</pre>
53  * </p>
54  */
55 public final class AndroidHttpClient implements HttpClient {
56
57   /**
58    * Create a new HttpClient with reasonable defaults (which you can update).
59    *
60    * @param userAgent to report in your HTTP requests.
61    * @return AndroidHttpClient for you to use for all your requests.
62    */
63   public static AndroidHttpClient newInstance(String userAgent) {
64     HttpParams params = new BasicHttpParams();
65
66     // Turn off stale checking.  Our connections break all the time anyway,
67     // and it's not worth it to pay the penalty of checking every time.
68     HttpConnectionParams.setStaleCheckingEnabled(params, false);
69
70     // Default connection and socket timeout of 20 seconds.  Tweak to taste.
71     HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
72     HttpConnectionParams.setSoTimeout(params, 20 * 1000);
73     HttpConnectionParams.setSocketBufferSize(params, 8192);
74
75     // Don't handle redirects -- return them to the caller.  Our code
76     // often wants to re-POST after a redirect, which we must do ourselves.
77     HttpClientParams.setRedirecting(params, false);
78
79     // Set the specified user agent and register standard protocols.
80     if (userAgent != null) {
81       HttpProtocolParams.setUserAgent(params, userAgent);
82     }
83     SchemeRegistry schemeRegistry = new SchemeRegistry();
84     schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
85     schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
86     ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
87
88     // We use a factory method to modify superclass initialization
89     // parameters without the funny call-a-static-method dance.
90     return new AndroidHttpClient(manager, params);
91   }
92
93   private final HttpClient delegate;
94
95
96   private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) {
97     this.delegate = new DelegateHttpClient(ccm, params);
98   }
99
100   /**
101    * Release resources associated with this client.  You must call this,
102    * or significant resources (sockets and memory) may be leaked.
103    */
104   public void close() {
105     getConnectionManager().shutdown();
106   }
107
108   public HttpParams getParams() {
109     return delegate.getParams();
110   }
111
112   public ClientConnectionManager getConnectionManager() {
113     return delegate.getConnectionManager();
114   }
115
116   public HttpResponse execute(HttpUriRequest request) throws IOException {
117     return delegate.execute(request);
118   }
119
120   public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException {
121     return delegate.execute(request, context);
122   }
123
124   public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException {
125     return delegate.execute(target, request);
126   }
127
128   public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException {
129     return delegate.execute(target, request, context);
130   }
131
132   public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException {
133     return delegate.execute(request, responseHandler);
134   }
135
136   public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context)
137       throws IOException {
138     return delegate.execute(request, responseHandler, context);
139   }
140
141   public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler)
142       throws IOException {
143     return delegate.execute(target, request, responseHandler);
144   }
145
146   public <T> T execute(HttpHost target, HttpRequest request,
147                        ResponseHandler<? extends T> responseHandler,
148                        HttpContext context) throws IOException {
149     return delegate.execute(target, request, responseHandler, context);
150   }
151
152   private static class DelegateHttpClient extends DefaultHttpClient {
153
154     private DelegateHttpClient(ClientConnectionManager ccm, HttpParams params) {
155       super(ccm, params);
156     }
157
158     @Override
159     protected HttpContext createHttpContext() {
160       // Same as DefaultHttpClient.createHttpContext() minus the
161       // cookie store.
162       HttpContext context = new BasicHttpContext();
163       context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
164       context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
165       context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
166       return context;
167     }
168   }
169
170 }