001/* 002 * Copyright 2012-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.web.client; 018 019import java.util.Collections; 020import java.util.LinkedHashMap; 021import java.util.Map; 022import java.util.function.Supplier; 023 024import org.springframework.beans.BeanUtils; 025import org.springframework.http.client.ClientHttpRequestFactory; 026import org.springframework.http.client.SimpleClientHttpRequestFactory; 027import org.springframework.util.ClassUtils; 028 029/** 030 * A supplier for {@link ClientHttpRequestFactory} that detects the preferred candidate 031 * based on the available implementations on the classpath. 032 * 033 * @author Stephane Nicoll 034 * @since 2.1.0 035 */ 036public class ClientHttpRequestFactorySupplier 037 implements Supplier<ClientHttpRequestFactory> { 038 039 private static final Map<String, String> REQUEST_FACTORY_CANDIDATES; 040 041 static { 042 Map<String, String> candidates = new LinkedHashMap<>(); 043 candidates.put("org.apache.http.client.HttpClient", 044 "org.springframework.http.client.HttpComponentsClientHttpRequestFactory"); 045 candidates.put("okhttp3.OkHttpClient", 046 "org.springframework.http.client.OkHttp3ClientHttpRequestFactory"); 047 REQUEST_FACTORY_CANDIDATES = Collections.unmodifiableMap(candidates); 048 } 049 050 @Override 051 public ClientHttpRequestFactory get() { 052 for (Map.Entry<String, String> candidate : REQUEST_FACTORY_CANDIDATES 053 .entrySet()) { 054 ClassLoader classLoader = getClass().getClassLoader(); 055 if (ClassUtils.isPresent(candidate.getKey(), classLoader)) { 056 Class<?> factoryClass = ClassUtils.resolveClassName(candidate.getValue(), 057 classLoader); 058 return (ClientHttpRequestFactory) BeanUtils 059 .instantiateClass(factoryClass); 060 } 061 } 062 return new SimpleClientHttpRequestFactory(); 063 } 064 065}