bb27034e24920b8a17a2bd6e7d49b2c808b0c381
[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.BasicHttpProcessor;
41 import org.apache.http.protocol.HttpContext;
42
43 import java.io.IOException;
44
45 /**
46  * <p>Subclass of the Apache {@link DefaultHttpClient} that is configured with
47  * reasonable default settings and registered schemes for Android, and
48  * also lets the user add {@link HttpRequestInterceptor} classes.
49  * Don't create this directly, use the {@link #newInstance} factory method.</p>
50  * <p/>
51  * <p>This client processes cookies but does not retain them by default.
52  * To retain cookies, simply add a cookie store to the HttpContext:
53  * <pre>context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);</pre>
54  * </p>
55  */
56 public final class AndroidHttpClient implements HttpClient {
57
58   /**
59    * Set if HTTP requests are blocked from being executed on this thread
60    */
61   private static final ThreadLocal<Boolean> sThreadBlocked =
62       new ThreadLocal<Boolean>();
63
64   /**
65    * Interceptor throws an exception if the executing thread is blocked
66    */
67   private static final HttpRequestInterceptor sThreadCheckInterceptor =
68       new HttpRequestInterceptor() {
69         public void process(HttpRequest request, HttpContext context) {
70           if (Boolean.TRUE.equals(sThreadBlocked.get())) {
71             throw new RuntimeException("This thread forbids HTTP requests");
72           }
73         }
74       };
75
76   /**
77    * Create a new HttpClient with reasonable defaults (which you can update).
78    *
79    * @param userAgent to report in your HTTP requests.
80    * @return AndroidHttpClient for you to use for all your requests.
81    */
82   public static AndroidHttpClient newInstance(String userAgent) {
83     HttpParams params = new BasicHttpParams();
84
85     // Turn off stale checking.  Our connections break all the time anyway,
86     // and it's not worth it to pay the penalty of checking every time.
87     HttpConnectionParams.setStaleCheckingEnabled(params, false);
88
89     // Default connection and socket timeout of 20 seconds.  Tweak to taste.
90     HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
91     HttpConnectionParams.setSoTimeout(params, 20 * 1000);
92     HttpConnectionParams.setSocketBufferSize(params, 8192);
93
94     // Don't handle redirects -- return them to the caller.  Our code
95     // often wants to re-POST after a redirect, which we must do ourselves.
96     HttpClientParams.setRedirecting(params, false);
97
98     // Set the specified user agent and register standard protocols.
99     HttpProtocolParams.setUserAgent(params, userAgent);
100     SchemeRegistry schemeRegistry = new SchemeRegistry();
101     schemeRegistry.register(new Scheme("http",
102         PlainSocketFactory.getSocketFactory(), 80));
103     schemeRegistry.register(new Scheme("https",
104         SSLSocketFactory.getSocketFactory(), 443));
105     ClientConnectionManager manager =
106         new ThreadSafeClientConnManager(params, schemeRegistry);
107
108     // We use a factory method to modify superclass initialization
109     // parameters without the funny call-a-static-method dance.
110     return new AndroidHttpClient(manager, params);
111   }
112
113   private final HttpClient delegate;
114
115
116   private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) {
117     this.delegate = new DefaultHttpClient(ccm, params) {
118       @Override
119       protected BasicHttpProcessor createHttpProcessor() {
120         // Add interceptor to prevent making requests from main thread.
121         BasicHttpProcessor processor = super.createHttpProcessor();
122         processor.addRequestInterceptor(sThreadCheckInterceptor);
123         return processor;
124       }
125
126       @Override
127       protected HttpContext createHttpContext() {
128         // Same as DefaultHttpClient.createHttpContext() minus the
129         // cookie store.
130         HttpContext context = new BasicHttpContext();
131         context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
132         context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
133         context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
134         return context;
135       }
136     };
137   }
138
139   /**
140    * Release resources associated with this client.  You must call this,
141    * or significant resources (sockets and memory) may be leaked.
142    */
143   public void close() {
144     getConnectionManager().shutdown();
145   }
146
147   public HttpParams getParams() {
148     return delegate.getParams();
149   }
150
151   public ClientConnectionManager getConnectionManager() {
152     return delegate.getConnectionManager();
153   }
154
155   public HttpResponse execute(HttpUriRequest request) throws IOException {
156     return delegate.execute(request);
157   }
158
159   public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException {
160     return delegate.execute(request, context);
161   }
162
163   public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException {
164     return delegate.execute(target, request);
165   }
166
167   public HttpResponse execute(HttpHost target, HttpRequest request,
168                               HttpContext context) throws IOException {
169     return delegate.execute(target, request, context);
170   }
171
172   public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException {
173     return delegate.execute(request, responseHandler);
174   }
175
176   public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context)
177       throws IOException {
178     return delegate.execute(request, responseHandler, context);
179   }
180
181   public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler)
182       throws IOException {
183     return delegate.execute(target, request, responseHandler);
184   }
185
186   public <T> T execute(HttpHost target, HttpRequest request,
187                        ResponseHandler<? extends T> responseHandler,
188                        HttpContext context)
189       throws IOException {
190     return delegate.execute(target, request, responseHandler, context);
191   }
192
193 }