import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.CacheControlStrategy; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import java.io.IOException; import java.io.InputStream; public class HttpCacheClientExample { public static void main(String[] args) throws IOException { CloseableHttpClient httpClient = createHttpClient(); HttpGet httpGet = new HttpGet("https://example.com/api/resource"); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { try (InputStream inputStream = entity.getContent()) { // ... } } httpClient.close(); } private static CloseableHttpClient createHttpClient() { SSLConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory(); ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainsf) .register("https", sslsf) .build(); BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(registry); RequestConfig config = RequestConfig.custom() .setConnectTimeout(5000) .setSocketTimeout(5000) .build(); CacheControlStrategy cacheControlStrategy = CacheControlStrategy.newNeverCacheStrategy(); CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connManager) .setDefaultRequestConfig(config) .setCacheControlStrategy(cacheControlStrategy) .build(); return httpClient; } }


上一篇:
下一篇:
切换中文