1 /* 2 * Copyright (C) 2017 The Android Open Source Project 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 package com.android.volley.toolbox; 17 18 import com.android.volley.AuthFailureError; 19 import com.android.volley.Header; 20 import com.android.volley.Request; 21 22 import org.apache.http.conn.ConnectTimeoutException; 23 24 import java.io.IOException; 25 import java.net.SocketTimeoutException; 26 import java.util.ArrayList; 27 import java.util.List; 28 import java.util.Map; 29 30 /** 31 * {@link BaseHttpStack} implementation wrapping a {@link HttpStack}. 32 * 33 * <p>{@link BasicNetwork} uses this if it is provided a {@link HttpStack} at construction time, 34 * allowing it to have one implementation based atop {@link BaseHttpStack}. 35 */ 36 @SuppressWarnings("deprecation") 37 class AdaptedHttpStack extends BaseHttpStack { 38 39 private final HttpStack mHttpStack; 40 41 AdaptedHttpStack(HttpStack httpStack) { 42 mHttpStack = httpStack; 43 } 44 45 @Override 46 public HttpResponse executeRequest( 47 Request<?> request, Map<String, String> additionalHeaders) 48 throws IOException, AuthFailureError { 49 org.apache.http.HttpResponse apacheResp; 50 try { 51 apacheResp = mHttpStack.performRequest(request, additionalHeaders); 52 } catch (ConnectTimeoutException e) { 53 // BasicNetwork won't know that this exception should be retried like a timeout, since 54 // it's an Apache-specific error, so wrap it in a standard timeout exception. 55 throw new SocketTimeoutException(e.getMessage()); 56 } 57 58 int statusCode = apacheResp.getStatusLine().getStatusCode(); 59 60 org.apache.http.Header[] headers = apacheResp.getAllHeaders(); 61 List<Header> headerList = new ArrayList<>(headers.length); 62 for (org.apache.http.Header header : headers) { 63 headerList.add(new Header(header.getName(), header.getValue())); 64 } 65 66 if (apacheResp.getEntity() == null) { 67 return new HttpResponse(statusCode, headerList); 68 } 69 70 long contentLength = apacheResp.getEntity().getContentLength(); 71 if ((int) contentLength != contentLength) { 72 throw new IOException("Response too large: " + contentLength); 73 } 74 75 return new HttpResponse( 76 statusCode, 77 headerList, 78 (int) apacheResp.getEntity().getContentLength(), 79 apacheResp.getEntity().getContent()); 80 } 81 } 82