64
64
65
65
import java .io .IOException ;
66
66
import java .io .InputStream ;
67
+ import java .io .OutputStream ;
67
68
import java .lang .ref .WeakReference ;
69
+ import java .net .HttpURLConnection ;
70
+ import java .net .MalformedURLException ;
71
+ import java .net .ProtocolException ;
72
+ import java .net .URL ;
68
73
import java .util .HashMap ;
69
74
import java .util .LinkedList ;
70
75
import java .util .List ;
73
78
import java .util .concurrent .Executors ;
74
79
import java .util .concurrent .Future ;
75
80
import java .util .concurrent .ThreadPoolExecutor ;
81
+ import java .util .concurrent .TimeUnit ;
76
82
import java .util .zip .GZIPInputStream ;
77
83
78
84
@@ -106,149 +112,17 @@ public class AsyncHttpClient {
106
112
private int maxConnections = DEFAULT_MAX_CONNECTIONS ;
107
113
private int timeout = DEFAULT_SOCKET_TIMEOUT ;
108
114
109
- private final OkHttpClient httpClient ;
110
- private final HttpContext httpContext ;
115
+ private final OkHttpClient httpClient = new OkHttpClient ();
111
116
private ThreadPoolExecutor threadPool ;
112
- private final Map <Context , List <WeakReference <Future <?>>>> requestMap ;
113
- private final Map <String , String > clientHeaderMap ;
117
+ // private final Map<Context, List<WeakReference<Future<?>>>> requestMap;
118
+ private final Map <String , String > clientHeaderMap = new HashMap < String , String >() ;
114
119
private boolean isUrlEncodingEnabled = true ;
115
120
116
121
/**
117
122
* Creates a new AsyncHttpClient with default constructor arguments values
118
123
*/
119
124
public AsyncHttpClient () {
120
- this (false , 80 , 443 );
121
- }
122
-
123
- /**
124
- * Creates a new AsyncHttpClient.
125
- *
126
- * @param httpPort non-standard HTTP-only port
127
- */
128
- public AsyncHttpClient (int httpPort ) {
129
- this (false , httpPort , 443 );
130
- }
131
-
132
- /**
133
- * Creates a new AsyncHttpClient.
134
- *
135
- * @param httpPort non-standard HTTP-only port
136
- * @param httpsPort non-standard HTTPS-only port
137
- */
138
- public AsyncHttpClient (int httpPort , int httpsPort ) {
139
- this (false , httpPort , httpsPort );
140
- }
141
-
142
- /**
143
- * Creates new AsyncHttpClient using given params
144
- *
145
- * @param fixNoHttpResponseException Whether to fix or not issue, by ommiting SSL verification
146
- * @param httpPort HTTP port to be used, must be greater than 0
147
- * @param httpsPort HTTPS port to be used, must be greater than 0
148
- */
149
- public AsyncHttpClient (boolean fixNoHttpResponseException , int httpPort , int httpsPort ) {
150
- this (getDefaultSchemeRegistry (fixNoHttpResponseException , httpPort , httpsPort ));
151
- }
152
-
153
- /**
154
- * Returns default instance of SchemeRegistry
155
- *
156
- * @param fixNoHttpResponseException Whether to fix or not issue, by ommiting SSL verification
157
- * @param httpPort HTTP port to be used, must be greater than 0
158
- * @param httpsPort HTTPS port to be used, must be greater than 0
159
- */
160
- private static SchemeRegistry getDefaultSchemeRegistry (boolean fixNoHttpResponseException , int httpPort , int httpsPort ) {
161
- if (fixNoHttpResponseException ) {
162
- Log .d (LOG_TAG , "Beware! Using the fix is insecure, as it doesn't verify SSL certificates." );
163
- }
164
-
165
- if (httpPort < 1 ) {
166
- httpPort = 80 ;
167
- Log .d (LOG_TAG , "Invalid HTTP port number specified, defaulting to 80" );
168
- }
169
-
170
- if (httpsPort < 1 ) {
171
- httpsPort = 443 ;
172
- Log .d (LOG_TAG , "Invalid HTTPS port number specified, defaulting to 443" );
173
- }
174
-
175
- // Fix to SSL flaw in API < ICS
176
- // See https://code.google.com/p/android/issues/detail?id=13117
177
- SSLSocketFactory sslSocketFactory ;
178
- if (fixNoHttpResponseException )
179
- sslSocketFactory = MySSLSocketFactory .getFixedSocketFactory ();
180
- else
181
- sslSocketFactory = SSLSocketFactory .getSocketFactory ();
182
-
183
- SchemeRegistry schemeRegistry = new SchemeRegistry ();
184
- schemeRegistry .register (new Scheme ("http" , PlainSocketFactory .getSocketFactory (), httpPort ));
185
- schemeRegistry .register (new Scheme ("https" , sslSocketFactory , httpsPort ));
186
-
187
- return schemeRegistry ;
188
- }
189
-
190
- /**
191
- * Creates a new AsyncHttpClient.
192
- *
193
- * @param schemeRegistry SchemeRegistry to be used
194
- */
195
- public AsyncHttpClient (SchemeRegistry schemeRegistry ) {
196
-
197
- BasicHttpParams httpParams = new BasicHttpParams ();
198
-
199
- ConnManagerParams .setTimeout (httpParams , timeout );
200
- ConnManagerParams .setMaxConnectionsPerRoute (httpParams , new ConnPerRouteBean (maxConnections ));
201
- ConnManagerParams .setMaxTotalConnections (httpParams , DEFAULT_MAX_CONNECTIONS );
202
-
203
- HttpConnectionParams .setSoTimeout (httpParams , timeout );
204
- HttpConnectionParams .setConnectionTimeout (httpParams , timeout );
205
- HttpConnectionParams .setTcpNoDelay (httpParams , true );
206
- HttpConnectionParams .setSocketBufferSize (httpParams , DEFAULT_SOCKET_BUFFER_SIZE );
207
-
208
- HttpProtocolParams .setVersion (httpParams , HttpVersion .HTTP_1_1 );
209
- HttpProtocolParams .setUserAgent (httpParams , String .format ("android-async-http/%s (http://loopj.com/android-async-http)" , VERSION ));
210
-
211
- ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager (httpParams , schemeRegistry );
212
-
213
- threadPool = (ThreadPoolExecutor ) Executors .newFixedThreadPool (DEFAULT_MAX_CONNECTIONS );
214
- requestMap = new WeakHashMap <Context , List <WeakReference <Future <?>>>>();
215
- clientHeaderMap = new HashMap <String , String >();
216
-
217
- httpContext = new SyncBasicHttpContext (new BasicHttpContext ());
218
- httpClient = new OkHttpClient (cm , httpParams );
219
- httpClient .setFollowProtocolRedirects ()
220
- httpClient .addRequestInterceptor (new HttpRequestInterceptor () {
221
- @ Override
222
- public void process (HttpRequest request , HttpContext context ) {
223
- if (!request .containsHeader (HEADER_ACCEPT_ENCODING )) {
224
- request .addHeader (HEADER_ACCEPT_ENCODING , ENCODING_GZIP );
225
- }
226
- for (String header : clientHeaderMap .keySet ()) {
227
- request .addHeader (header , clientHeaderMap .get (header ));
228
- }
229
- }
230
- });
231
-
232
- httpClient .addResponseInterceptor (new HttpResponseInterceptor () {
233
- @ Override
234
- public void process (HttpResponse response , HttpContext context ) {
235
- final HttpEntity entity = response .getEntity ();
236
- if (entity == null ) {
237
- return ;
238
- }
239
- final Header encoding = entity .getContentEncoding ();
240
- if (encoding != null ) {
241
- for (HeaderElement element : encoding .getElements ()) {
242
- if (element .getName ().equalsIgnoreCase (ENCODING_GZIP )) {
243
- response .setEntity (new InflatingEntity (entity ));
244
- break ;
245
- }
246
- }
247
- }
248
- }
249
- });
250
-
251
- httpClient .setHttpRequestRetryHandler (new RetryHandler (DEFAULT_MAX_RETRIES , DEFAULT_RETRY_SLEEP_TIME_MILLIS ));
125
+
252
126
}
253
127
254
128
/**
@@ -258,18 +132,8 @@ public void process(HttpResponse response, HttpContext context) {
258
132
*
259
133
* @return underlying HttpClient instance
260
134
*/
261
- public HttpClient getHttpClient () {
262
- return this .httpClient ;
263
- }
264
-
265
- /**
266
- * Get the underlying HttpContext instance. This is useful for getting and setting fine-grained
267
- * settings for requests by accessing the context's attributes such as the CookieStore.
268
- *
269
- * @return underlying HttpContext instance
270
- */
271
- public HttpContext getHttpContext () {
272
- return this .httpContext ;
135
+ public OkHttpClient getHttpClient () {
136
+ return httpClient ;
273
137
}
274
138
275
139
/**
@@ -354,15 +218,14 @@ public int getTimeout() {
354
218
* Set the connection and socket timeout. By default, 10 seconds.
355
219
*
356
220
* @param timeout the connect/socket timeout in milliseconds, at least 1 second
221
+ * @deprecated use {@link #setTimeout(long, TimeUnit)} instead
357
222
*/
358
223
public void setTimeout (int timeout ) {
359
- if (timeout < 1000 )
360
- timeout = DEFAULT_SOCKET_TIMEOUT ;
361
- this .timeout = timeout ;
362
- final HttpParams httpParams = this .httpClient .getParams ();
363
- ConnManagerParams .setTimeout (httpParams , this .timeout );
364
- HttpConnectionParams .setSoTimeout (httpParams , this .timeout );
365
- HttpConnectionParams .setConnectionTimeout (httpParams , this .timeout );
224
+ setTimeout (timeout , TimeUnit .MILLISECONDS );
225
+ }
226
+
227
+ public void setTimeout (long timeout , TimeUnit unit ) {
228
+ httpClient .setConnectTimeout (timeout , unit );
366
229
}
367
230
368
231
/**
@@ -884,30 +747,33 @@ public RequestHandle delete(Context context, String url, Header[] headers, Reque
884
747
* HttpPost, HttpGet, HttpPut, etc.
885
748
* @return RequestHandle of future request process
886
749
*/
887
- protected RequestHandle sendRequest (OkHttpClient client , HttpContext httpContext , HttpUriRequest uriRequest , String contentType , ResponseHandlerInterface responseHandler , Context context ) {
888
- if (contentType != null ) {
889
- uriRequest .addHeader ("Content-Type" , contentType );
750
+ protected RequestHandle sendRequest (OkHttpClient client , HttpUriRequest uriRequest , String contentType , ResponseHandlerInterface responseHandler , Context context ) {
751
+ HttpURLConnection connection = null ;
752
+ try {
753
+ connection = client .open (uriRequest .getURI ().toURL ());
754
+ connection .setRequestMethod (uriRequest .getMethod ()); //TODO write the params to connection.getOutputStream(void)
755
+ for (Map .Entry <String , String > header : clientHeaderMap .entrySet ()) {
756
+ connection .setRequestProperty (header .getKey (), header .getValue ());
757
+ }
758
+ if (contentType != null ) {
759
+ uriRequest .addHeader ("Content-Type" , contentType );
760
+ connection .setRequestProperty ("Content-Type" , contentType );
761
+ }
762
+ } catch (ProtocolException e ) {
763
+
764
+ } catch (MalformedURLException e ) {
765
+
890
766
}
891
767
892
768
responseHandler .setRequestHeaders (uriRequest .getAllHeaders ());
893
769
responseHandler .setRequestURI (uriRequest .getURI ());
894
770
895
- Future <?> request = threadPool .submit (new AsyncHttpRequest (client , httpContext , uriRequest , responseHandler ));
896
-
897
- if (context != null ) {
898
- // Add request to request map
899
- List <WeakReference <Future <?>>> requestList = requestMap .get (context );
900
- if (requestList == null ) {
901
- requestList = new LinkedList <WeakReference <Future <?>>>();
902
- requestMap .put (context , requestList );
903
- }
904
-
905
- requestList .add (new WeakReference <Future <?>>(request ));
906
-
907
- // TODO: Remove dead weakrefs from requestLists?
771
+ if (connection != null ) {
772
+ Future <?> request = threadPool .submit (new AsyncHttpRequest (connection , uriRequest , responseHandler ));
773
+ return new RequestHandle (request );
908
774
}
909
-
910
- return new RequestHandle ( request ) ;
775
+
776
+ return null ;
911
777
}
912
778
913
779
/**
0 commit comments