2 * Copyright (C) 2008 ZXing authors
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.zxing.client.android;
19 import android.util.Log;
20 import org.apache.http.Header;
21 import org.apache.http.HttpEntity;
22 import org.apache.http.HttpEntityEnclosingRequest;
23 import org.apache.http.HttpException;
24 import org.apache.http.HttpHost;
25 import org.apache.http.HttpMessage;
26 import org.apache.http.HttpRequest;
27 import org.apache.http.HttpRequestInterceptor;
28 import org.apache.http.HttpResponse;
29 import org.apache.http.client.HttpClient;
30 import org.apache.http.client.ResponseHandler;
31 import org.apache.http.client.methods.HttpUriRequest;
32 import org.apache.http.client.params.HttpClientParams;
33 import org.apache.http.client.protocol.ClientContext;
34 import org.apache.http.conn.ClientConnectionManager;
35 import org.apache.http.conn.scheme.PlainSocketFactory;
36 import org.apache.http.conn.scheme.Scheme;
37 import org.apache.http.conn.scheme.SchemeRegistry;
38 import org.apache.http.conn.ssl.SSLSocketFactory;
39 import org.apache.http.entity.AbstractHttpEntity;
40 import org.apache.http.entity.ByteArrayEntity;
41 import org.apache.http.impl.client.DefaultHttpClient;
42 import org.apache.http.impl.client.RequestWrapper;
43 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
44 import org.apache.http.params.BasicHttpParams;
45 import org.apache.http.params.HttpConnectionParams;
46 import org.apache.http.params.HttpParams;
47 import org.apache.http.params.HttpProtocolParams;
48 import org.apache.http.protocol.BasicHttpContext;
49 import org.apache.http.protocol.BasicHttpProcessor;
50 import org.apache.http.protocol.HttpContext;
52 import java.io.ByteArrayOutputStream;
53 import java.io.IOException;
54 import java.io.InputStream;
55 import java.io.OutputStream;
57 import java.util.zip.GZIPInputStream;
58 import java.util.zip.GZIPOutputStream;
61 * <p>Subclass of the Apache {@link DefaultHttpClient} that is configured with
62 * reasonable default settings and registered schemes for Android, and
63 * also lets the user add {@link HttpRequestInterceptor} classes.
64 * Don't create this directly, use the {@link #newInstance} factory method.</p>
66 * <p>This client processes cookies but does not retain them by default.
67 * To retain cookies, simply add a cookie store to the HttpContext:
68 * <pre>context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);</pre>
71 public final class AndroidHttpClient implements HttpClient {
73 // Gzip of data shorter than this probably won't be worthwhile
74 private static final long DEFAULT_SYNC_MIN_GZIP_BYTES = 256;
76 private static final String TAG = "AndroidHttpClient";
80 * Set if HTTP requests are blocked from being executed on this thread
82 private static final ThreadLocal<Boolean> sThreadBlocked =
83 new ThreadLocal<Boolean>();
86 * Interceptor throws an exception if the executing thread is blocked
88 private static final HttpRequestInterceptor sThreadCheckInterceptor =
89 new HttpRequestInterceptor() {
90 public void process(HttpRequest request, HttpContext context) {
91 if (sThreadBlocked.get() != null && sThreadBlocked.get()) {
92 throw new RuntimeException("This thread forbids HTTP requests");
98 * Create a new HttpClient with reasonable defaults (which you can update).
100 * @param userAgent to report in your HTTP requests.
101 * @return AndroidHttpClient for you to use for all your requests.
103 public static AndroidHttpClient newInstance(String userAgent) {
104 HttpParams params = new BasicHttpParams();
106 // Turn off stale checking. Our connections break all the time anyway,
107 // and it's not worth it to pay the penalty of checking every time.
108 HttpConnectionParams.setStaleCheckingEnabled(params, false);
110 // Default connection and socket timeout of 20 seconds. Tweak to taste.
111 HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
112 HttpConnectionParams.setSoTimeout(params, 20 * 1000);
113 HttpConnectionParams.setSocketBufferSize(params, 8192);
115 // Don't handle redirects -- return them to the caller. Our code
116 // often wants to re-POST after a redirect, which we must do ourselves.
117 HttpClientParams.setRedirecting(params, false);
119 // Set the specified user agent and register standard protocols.
120 HttpProtocolParams.setUserAgent(params, userAgent);
121 SchemeRegistry schemeRegistry = new SchemeRegistry();
122 schemeRegistry.register(new Scheme("http",
123 PlainSocketFactory.getSocketFactory(), 80));
124 schemeRegistry.register(new Scheme("https",
125 SSLSocketFactory.getSocketFactory(), 443));
126 ClientConnectionManager manager =
127 new ThreadSafeClientConnManager(params, schemeRegistry);
129 // We use a factory method to modify superclass initialization
130 // parameters without the funny call-a-static-method dance.
131 return new AndroidHttpClient(manager, params);
134 private final HttpClient delegate;
136 private RuntimeException mLeakedException = new IllegalStateException(
137 "AndroidHttpClient created and never closed");
139 private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) {
140 this.delegate = new DefaultHttpClient(ccm, params) {
142 protected BasicHttpProcessor createHttpProcessor() {
143 // Add interceptor to prevent making requests from main thread.
144 BasicHttpProcessor processor = super.createHttpProcessor();
145 processor.addRequestInterceptor(sThreadCheckInterceptor);
146 processor.addRequestInterceptor(new CurlLogger());
152 protected HttpContext createHttpContext() {
153 // Same as DefaultHttpClient.createHttpContext() minus the
155 HttpContext context = new BasicHttpContext();
156 context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
157 context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
158 context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
165 protected void finalize() throws Throwable {
167 if (mLeakedException != null) {
168 Log.e(TAG, "Leak found", mLeakedException);
169 mLeakedException = null;
174 * Block this thread from executing HTTP requests.
175 * Used to guard against HTTP requests blocking the main application thread.
177 * @param blocked if HTTP requests run on this thread should be denied
179 public static void setThreadBlocked(boolean blocked) {
180 sThreadBlocked.set(blocked);
184 * Modifies a request to indicate to the server that we would like a
185 * gzipped response. (Uses the "Accept-Encoding" HTTP header.)
187 * @param request the request to modify
188 * @see #getUngzippedContent
190 public static void modifyRequestToAcceptGzipResponse(HttpMessage request) {
191 request.addHeader("Accept-Encoding", "gzip");
195 * Gets the input stream from a response entity. If the entity is gzipped
196 * then this will get a stream over the uncompressed data.
198 * @param entity the entity whose content should be read
199 * @return the input stream to read from
200 * @throws IOException
202 public static InputStream getUngzippedContent(HttpEntity entity) throws IOException {
203 InputStream responseStream = entity.getContent();
204 if (responseStream == null) {
205 return responseStream;
207 Header header = entity.getContentEncoding();
208 if (header == null) {
209 return responseStream;
211 String contentEncoding = header.getValue();
212 if (contentEncoding == null) {
213 return responseStream;
215 if (contentEncoding.contains("gzip")) responseStream = new GZIPInputStream(responseStream);
216 return responseStream;
220 * Release resources associated with this client. You must call this,
221 * or significant resources (sockets and memory) may be leaked.
223 public void close() {
224 if (mLeakedException != null) {
225 getConnectionManager().shutdown();
226 mLeakedException = null;
230 public HttpParams getParams() {
231 return delegate.getParams();
234 public ClientConnectionManager getConnectionManager() {
235 return delegate.getConnectionManager();
238 public HttpResponse execute(HttpUriRequest request) throws IOException {
239 return delegate.execute(request);
242 public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException {
243 return delegate.execute(request, context);
246 public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException {
247 return delegate.execute(target, request);
250 public HttpResponse execute(HttpHost target, HttpRequest request,
251 HttpContext context) throws IOException {
252 return delegate.execute(target, request, context);
255 public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException {
256 return delegate.execute(request, responseHandler);
259 public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context)
261 return delegate.execute(request, responseHandler, context);
264 public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler)
266 return delegate.execute(target, request, responseHandler);
269 public <T> T execute(HttpHost target, HttpRequest request,
270 ResponseHandler<? extends T> responseHandler,
273 return delegate.execute(target, request, responseHandler, context);
277 * Compress data to send to server.
278 * Creates a Http Entity holding the gzipped data.
279 * The data will not be compressed if it is too short.
281 * @param data The bytes to compress
282 * @return Entity holding the data
284 public static AbstractHttpEntity getCompressedEntity(byte data[]) throws IOException {
285 AbstractHttpEntity entity;
286 if (data.length < getMinGzipSize()) {
287 entity = new ByteArrayEntity(data);
289 ByteArrayOutputStream arr = new ByteArrayOutputStream();
290 OutputStream zipper = new GZIPOutputStream(arr);
296 entity = new ByteArrayEntity(arr.toByteArray());
297 entity.setContentEncoding("gzip");
303 * Retrieves the minimum size for compressing data.
304 * Shorter data will not be compressed.
306 private static long getMinGzipSize() {
307 return DEFAULT_SYNC_MIN_GZIP_BYTES;
310 /* cURL logging support. */
313 * Logging tag and level.
315 private static final class LoggingConfiguration {
317 private final String tag;
318 private final int level;
320 private LoggingConfiguration(String tag, int level) {
326 * Returns true if logging is turned on for this configuration.
328 private boolean isLoggable() {
329 return Log.isLoggable(tag, level);
333 * Prints a message using this configuration.
335 private void println(String message) {
336 Log.println(level, tag, message);
341 * cURL logging configuration.
343 private volatile LoggingConfiguration curlConfiguration;
346 * Enables cURL request logging for this client.
348 * @param name to log messages with
349 * @param level at which to log messages (see {@link android.util.Log})
351 public void enableCurlLogging(String name, int level) {
353 throw new NullPointerException("name");
355 if (level < Log.VERBOSE || level > Log.ASSERT) {
356 throw new IllegalArgumentException("Level is out of range ["
357 + Log.VERBOSE + ".." + Log.ASSERT + "]");
360 curlConfiguration = new LoggingConfiguration(name, level);
364 * Disables cURL logging for this client.
366 public void disableCurlLogging() {
367 curlConfiguration = null;
371 * Logs cURL commands equivalent to requests.
373 private final class CurlLogger implements HttpRequestInterceptor {
374 public final void process(HttpRequest request, HttpContext context)
376 LoggingConfiguration configuration = curlConfiguration;
377 if (configuration != null
378 && configuration.isLoggable()
379 && request instanceof HttpUriRequest) {
380 configuration.println(toCurl((HttpUriRequest) request));
385 * Generates a cURL command equivalent to the given request.
387 private String toCurl(HttpUriRequest request) throws IOException {
388 StringBuilder builder = new StringBuilder();
390 builder.append("curl ");
392 for (Header header : request.getAllHeaders()) {
393 builder.append("--header \"");
394 builder.append(header.toString().trim());
395 builder.append("\" ");
398 URI uri = request.getURI();
400 // If this is a wrapped request, use the URI from the original
401 // request instead. getURI() on the wrapper seems to return a
402 // relative URI. We want an absolute URI.
403 if (request instanceof RequestWrapper) {
404 HttpRequest original = ((RequestWrapper) request).getOriginal();
405 if (original instanceof HttpUriRequest) {
406 uri = ((HttpUriRequest) original).getURI();
414 if (request instanceof HttpEntityEnclosingRequest) {
415 HttpEntityEnclosingRequest entityRequest =
416 (HttpEntityEnclosingRequest) request;
417 HttpEntity entity = entityRequest.getEntity();
418 if (entity != null && entity.isRepeatable()) {
419 if (entity.getContentLength() < 1024) {
420 OutputStream stream = new ByteArrayOutputStream();
421 entity.writeTo(stream);
422 String entityString = stream.toString();
423 // TODO: Check the content type, too.
424 builder.append(" --data-ascii \"").append(entityString).append('"');
426 builder.append(" [TOO MUCH DATA TO INCLUDE]");
431 return builder.toString();