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 public 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);
293 entity = new ByteArrayEntity(arr.toByteArray());
294 entity.setContentEncoding("gzip");
300 * Retrieves the minimum size for compressing data.
301 * Shorter data will not be compressed.
303 public static long getMinGzipSize() {
304 return DEFAULT_SYNC_MIN_GZIP_BYTES;
307 /* cURL logging support. */
310 * Logging tag and level.
312 private static class LoggingConfiguration {
314 private final String tag;
315 private final int level;
317 private LoggingConfiguration(String tag, int level) {
323 * Returns true if logging is turned on for this configuration.
325 private boolean isLoggable() {
326 return Log.isLoggable(tag, level);
330 * Prints a message using this configuration.
332 private void println(String message) {
333 Log.println(level, tag, message);
338 * cURL logging configuration.
340 private volatile LoggingConfiguration curlConfiguration;
343 * Enables cURL request logging for this client.
345 * @param name to log messages with
346 * @param level at which to log messages (see {@link android.util.Log})
348 public void enableCurlLogging(String name, int level) {
350 throw new NullPointerException("name");
352 if (level < Log.VERBOSE || level > Log.ASSERT) {
353 throw new IllegalArgumentException("Level is out of range ["
354 + Log.VERBOSE + ".." + Log.ASSERT + "]");
357 curlConfiguration = new LoggingConfiguration(name, level);
361 * Disables cURL logging for this client.
363 public void disableCurlLogging() {
364 curlConfiguration = null;
368 * Logs cURL commands equivalent to requests.
370 private class CurlLogger implements HttpRequestInterceptor {
371 public void process(HttpRequest request, HttpContext context)
372 throws HttpException, IOException {
373 LoggingConfiguration configuration = curlConfiguration;
374 if (configuration != null
375 && configuration.isLoggable()
376 && request instanceof HttpUriRequest) {
377 configuration.println(toCurl((HttpUriRequest) request));
382 * Generates a cURL command equivalent to the given request.
384 private String toCurl(HttpUriRequest request) throws IOException {
385 StringBuilder builder = new StringBuilder();
387 builder.append("curl ");
389 for (Header header : request.getAllHeaders()) {
390 builder.append("--header \"");
391 builder.append(header.toString().trim());
392 builder.append("\" ");
395 URI uri = request.getURI();
397 // If this is a wrapped request, use the URI from the original
398 // request instead. getURI() on the wrapper seems to return a
399 // relative URI. We want an absolute URI.
400 if (request instanceof RequestWrapper) {
401 HttpRequest original = ((RequestWrapper) request).getOriginal();
402 if (original instanceof HttpUriRequest) {
403 uri = ((HttpUriRequest) original).getURI();
411 if (request instanceof HttpEntityEnclosingRequest) {
412 HttpEntityEnclosingRequest entityRequest =
413 (HttpEntityEnclosingRequest) request;
414 HttpEntity entity = entityRequest.getEntity();
415 if (entity != null && entity.isRepeatable()) {
416 if (entity.getContentLength() < 1024) {
417 ByteArrayOutputStream stream = new ByteArrayOutputStream();
418 entity.writeTo(stream);
419 String entityString = stream.toString();
420 // TODO: Check the content type, too.
421 builder.append(" --data-ascii \"").append(entityString).append('"');
423 builder.append(" [TOO MUCH DATA TO INCLUDE]");
428 return builder.toString();