001/* 002 * acme4j - Java ACME client 003 * 004 * Copyright (C) 2015 Richard "Shred" Körber 005 * http://acme4j.shredzone.org 006 * 007 * Licensed under the Apache License, Version 2.0 (the "License"); 008 * you may not use this file except in compliance with the License. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 013 */ 014package org.shredzone.acme4j.connector; 015 016import java.io.IOException; 017import java.io.InputStream; 018import java.net.HttpURLConnection; 019import java.net.URL; 020import java.util.Properties; 021 022import org.slf4j.LoggerFactory; 023 024/** 025 * A generic HTTP connector. It connects to the given URI with a 10 seconds connection and 026 * read timeout. 027 * <p> 028 * Subclasses may reconfigure the {@link HttpURLConnection} and pin it to a concrete SSL 029 * certificate. 030 */ 031public class HttpConnector { 032 033 private static final int TIMEOUT = 10000; 034 private static final String USER_AGENT; 035 036 static { 037 StringBuilder agent = new StringBuilder("acme4j"); 038 039 try (InputStream in = HttpConnector.class.getResourceAsStream("/org/shredzone/acme4j/version.properties")) { 040 Properties prop = new Properties(); 041 prop.load(in); 042 agent.append('/').append(prop.getProperty("version")); 043 } catch (Exception ex) { 044 // Ignore, just don't use a version 045 LoggerFactory.getLogger(HttpConnector.class).warn("Could not read library version", ex); 046 } 047 048 agent.append(" Java/").append(System.getProperty("java.version")); 049 USER_AGENT = agent.toString(); 050 } 051 052 /** 053 * Returns the default User-Agent to be used. 054 * 055 * @return User-Agent 056 */ 057 public static String defaultUserAgent() { 058 return USER_AGENT; 059 } 060 061 /** 062 * Opens a {@link HttpURLConnection} to the given {@link URL}. 063 * 064 * @param url 065 * {@link URL} to connect to 066 * @return {@link HttpURLConnection} connected to the {@link URL} 067 */ 068 public HttpURLConnection openConnection(URL url) throws IOException { 069 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 070 configure(conn); 071 return conn; 072 } 073 074 /** 075 * Configures the new {@link HttpURLConnection}. 076 * <p> 077 * This implementation sets reasonable timeouts, forbids caching, and sets an user 078 * agent. 079 * 080 * @param conn 081 * {@link HttpURLConnection} to configure. 082 */ 083 protected void configure(HttpURLConnection conn) { 084 conn.setConnectTimeout(TIMEOUT); 085 conn.setReadTimeout(TIMEOUT); 086 conn.setUseCaches(false); 087 conn.setRequestProperty("User-Agent", USER_AGENT); 088 } 089 090}