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.server.cts.netstats;
17 
18 import android.net.TrafficStats;
19 import android.util.Log;
20 
21 import androidx.test.runner.AndroidJUnit4;
22 
23 import org.junit.Test;
24 import org.junit.runner.RunWith;
25 
26 import java.net.URL;
27 
28 import javax.net.ssl.HttpsURLConnection;
29 
30 /**
31  * Used by NetstatsIncidentTest.  Makes some network requests so "dumpsys netstats" will have
32  * something to show.
33  */
34 @RunWith(AndroidJUnit4.class)
35 public class NetstatsDeviceTest {
36     private static final String TAG = "NetstatsDeviceTest";
37 
38     private static final int NET_TAG = 123123123;
39 
40     @Test
testDoNetworkWithoutTagging()41     public void testDoNetworkWithoutTagging() throws Exception {
42         Log.i(TAG, "testDoNetworkWithoutTagging");
43 
44         makeNetworkRequest();
45     }
46 
47     @Test
testDoNetworkWithTagging()48     public void testDoNetworkWithTagging() throws Exception {
49         Log.i(TAG, "testDoNetworkWithTagging");
50 
51         TrafficStats.getAndSetThreadStatsTag(NET_TAG);
52         makeNetworkRequest();
53     }
54 
makeNetworkRequest()55     private void makeNetworkRequest() throws Exception {
56         final URL url = new URL("https://www.android.com/");
57         final HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
58         HttpsURLConnection.setFollowRedirects(true);
59         try {
60             final int status = urlConnection.getResponseCode();
61 
62             Log.i(TAG, "Response code from " + url + ": " + status);
63 
64             // Doesn't matter what response code we got.  We touched the network, which is enough.
65         } finally {
66             urlConnection.disconnect();
67         }
68     }
69 }
70