1 /* 2 * Copyright (C) 2009 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 17 package com.squareup.okhttp.internal.http; 18 19 import com.squareup.okhttp.OkHttpClient; 20 import com.squareup.okhttp.OkUrlFactory; 21 import com.squareup.okhttp.Protocol; 22 import com.squareup.okhttp.internal.Util; 23 import java.io.BufferedReader; 24 import java.io.InputStreamReader; 25 import java.net.URL; 26 import java.util.List; 27 import javax.net.ssl.HostnameVerifier; 28 import javax.net.ssl.HttpsURLConnection; 29 import javax.net.ssl.SSLSession; 30 31 import static com.squareup.okhttp.internal.http.OkHeaders.SELECTED_PROTOCOL; 32 33 public final class ExternalHttp2Example { 34 public static void main(String[] args) throws Exception { 35 URL url = new URL("https://twitter.com"); 36 OkHttpClient client = new OkHttpClient() 37 .setProtocols(Util.immutableList(Protocol.HTTP_2, Protocol.HTTP_1_1)); 38 HttpsURLConnection connection = (HttpsURLConnection) new OkUrlFactory(client) 39 .open(url); 40 41 connection.setHostnameVerifier(new HostnameVerifier() { 42 @Override public boolean verify(String s, SSLSession sslSession) { 43 System.out.println("VERIFYING " + s); 44 return true; 45 } 46 }); 47 48 int responseCode = connection.getResponseCode(); 49 System.out.println(responseCode); 50 List<String> protocolValues = connection.getHeaderFields().get(SELECTED_PROTOCOL); 51 // If null, probably you didn't add jetty's alpn jar to your boot classpath! 52 if (protocolValues != null && !protocolValues.isEmpty()) { 53 System.out.println("PROTOCOL " + protocolValues.get(0)); 54 } 55 56 BufferedReader reader = 57 new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); 58 String line; 59 while ((line = reader.readLine()) != null) { 60 System.out.println(line); 61 } 62 } 63 } 64