001/* 002 * Copyright 2016 The AppAuth for Android Authors. All Rights Reserved. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the 010 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 011 * express or implied. See the License for the specific language governing permissions and 012 * limitations under the License. 013 */ 014 015package net.openid.appauth.connectivity; 016 017import android.net.Uri; 018import androidx.annotation.NonNull; 019 020import net.openid.appauth.Preconditions; 021 022import java.io.IOException; 023import java.net.HttpURLConnection; 024import java.net.URL; 025import java.util.concurrent.TimeUnit; 026 027/** 028 * Creates {@link java.net.HttpURLConnection} instances using the default, platform-provided 029 * mechanism, with sensible production defaults. 030 */ 031public final class DefaultConnectionBuilder implements ConnectionBuilder { 032 033 /** 034 * The singleton instance of the default connection builder. 035 */ 036 public static final DefaultConnectionBuilder INSTANCE = new DefaultConnectionBuilder(); 037 038 private static final int CONNECTION_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(15); 039 private static final int READ_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(10); 040 041 private static final String HTTPS_SCHEME = "https"; 042 043 private DefaultConnectionBuilder() { 044 // no need to construct instances of this type 045 } 046 047 @NonNull 048 @Override 049 public HttpURLConnection openConnection(@NonNull Uri uri) throws IOException { 050 Preconditions.checkNotNull(uri, "url must not be null"); 051 Preconditions.checkArgument(HTTPS_SCHEME.equals(uri.getScheme()), 052 "only https connections are permitted"); 053 HttpURLConnection conn = (HttpURLConnection) new URL(uri.toString()).openConnection(); 054 conn.setConnectTimeout(CONNECTION_TIMEOUT_MS); 055 conn.setReadTimeout(READ_TIMEOUT_MS); 056 conn.setInstanceFollowRedirects(false); 057 return conn; 058 } 059}