1 /* 2 * Copyright (C) 2011 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 android.net.http.cts; 17 18 import org.apache.http.HttpResponse; 19 import org.apache.http.client.ClientProtocolException; 20 import org.apache.http.client.HttpClient; 21 import org.apache.http.client.methods.HttpGet; 22 import org.apache.http.impl.client.DefaultHttpClient; 23 24 import android.net.Uri; 25 import android.test.AndroidTestCase; 26 import android.webkit.cts.CtsTestServer; 27 28 import java.io.IOException; 29 import java.io.InputStream; 30 import java.util.ArrayList; 31 import java.util.List; 32 33 public class ApacheHttpClientTest extends AndroidTestCase { 34 35 private static final int NUM_DOWNLOADS = 20; 36 37 private static final int SMALL_DOWNLOAD_SIZE = 100 * 1024; 38 39 private CtsTestServer mWebServer; 40 41 @Override 42 protected void setUp() throws Exception { 43 super.setUp(); 44 mWebServer = new CtsTestServer(mContext); 45 } 46 47 @Override 48 protected void tearDown() throws Exception { 49 super.tearDown(); 50 mWebServer.shutdown(); 51 } 52 53 public void testExecute() throws Exception { 54 downloadMultipleFiles(); 55 } 56 57 private void downloadMultipleFiles() throws ClientProtocolException, IOException { 58 List<HttpResponse> responses = new ArrayList<HttpResponse>(); 59 for (int i = 0; i < NUM_DOWNLOADS; i++) { 60 HttpClient httpClient = new DefaultHttpClient(); 61 HttpGet request = new HttpGet(getSmallDownloadUrl(i).toString()); 62 HttpResponse response = httpClient.execute(request); 63 responses.add(response); 64 } 65 66 for (int i = 0; i < NUM_DOWNLOADS; i++) { 67 assertDownloadResponse("Download " + i, SMALL_DOWNLOAD_SIZE, responses.get(i)); 68 } 69 } 70 71 private Uri getSmallDownloadUrl(int index) { 72 return Uri.parse(mWebServer.getTestDownloadUrl("cts-small-download-" + index, 73 SMALL_DOWNLOAD_SIZE)); 74 } 75 76 private void assertDownloadResponse(String message, int expectedNumBytes, HttpResponse response) 77 throws IllegalStateException, IOException { 78 byte[] buffer = new byte[4096]; 79 assertEquals(200, response.getStatusLine().getStatusCode()); 80 81 InputStream stream = response.getEntity().getContent(); 82 int numBytes = 0; 83 while (true) { 84 int bytesRead = stream.read(buffer); 85 if (bytesRead < 0) { 86 break; 87 } else { 88 numBytes += bytesRead; 89 } 90 } 91 assertEquals(message, expectedNumBytes, numBytes); 92 } 93 } 94