001package com.hfg.util.io;
002
003
004import java.io.IOException;
005import java.net.HttpURLConnection;
006import java.net.InetSocketAddress;
007import java.net.Proxy;
008import java.net.URL;
009import java.net.URLEncoder;
010import java.security.SecureRandom;
011import java.security.cert.X509Certificate;
012import java.util.Collection;
013import java.util.logging.Logger;
014import javax.net.ssl.HostnameVerifier;
015import javax.net.ssl.HttpsURLConnection;
016import javax.net.ssl.SSLContext;
017import javax.net.ssl.SSLSession;
018import javax.net.ssl.TrustManager;
019import javax.net.ssl.X509TrustManager;
020import javax.servlet.http.Cookie;
021
022import com.hfg.util.StringBuilderPlus;
023import com.hfg.util.StringUtil;
024import com.hfg.util.collection.CollectionUtil;
025
026//------------------------------------------------------------------------------
027/**
028 * HTTP utility functions.
029 *
030 * @author J. Alex Taylor, hairyfatguy.com
031 */
032//------------------------------------------------------------------------------
033// com.hfg XML/HTML Coding Library
034//
035// This library is free software; you can redistribute it and/or
036// modify it under the terms of the GNU Lesser General Public
037// License as published by the Free Software Foundation; either
038// version 2.1 of the License, or (at your option) any later version.
039//
040// This library is distributed in the hope that it will be useful,
041// but WITHOUT ANY WARRANTY; without even the implied warranty of
042// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
043// Lesser General Public License for more details.
044//
045// You should have received a copy of the GNU Lesser General Public
046// License along with this library; if not, write to the Free Software
047// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
048//
049// J. Alex Taylor, President, Founder, CEO, COO, CFO, OOPS hairyfatguy.com
050// jataylor@hairyfatguy.com
051//------------------------------------------------------------------------------
052public class HTTPUtil
053{
054   private final static Logger LOGGER = Logger.getLogger(HTTPUtil.class.getName());
055
056   //---------------------------------------------------------------------------
057   public static HttpURLConnection openConnection(String inURL)
058         throws IOException
059   {
060      return openConnection(inURL, null, null);
061   }
062
063   //---------------------------------------------------------------------------
064   public static HttpURLConnection openConnection(String inURL, ProxyConfig inProxyConfig, Collection<Cookie> inCookies)
065         throws IOException
066   {
067      URL url = new URL(inURL);
068
069      HttpURLConnection conn;
070
071      // Proxy settings?
072      if (inProxyConfig != null)
073      {
074         Integer port = inProxyConfig.getPort();
075         if (null == port)
076         {
077            if (url.getProtocol().equalsIgnoreCase("HTTP"))
078            {
079               port = 80;
080            }
081            else if (url.getProtocol().equalsIgnoreCase("HTTPS"))
082            {
083               port = 443;
084            }
085         }
086
087         LOGGER.fine("Setting HTTP proxy host: " + inProxyConfig.getHost() + ":" + port);
088
089         Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(inProxyConfig.getHost(), port));
090         conn = (HttpURLConnection) url.openConnection(proxy);
091
092         /* TODO
093         LoginCredentials credentials = inProxyConfig.getCredentials();
094         if (credentials != null)
095         {
096            Authenticator authenticator = new Authenticator()
097            {
098               public PasswordAuthentication getPasswordAuthentication()
099               {
100                  return (new PasswordAuthentication("user",
101                                                     "password".toCharArray()));
102               }
103            };
104            Authenticator.setDefault(authenticator);
105         } */
106      }
107      else
108      {
109         conn = (HttpURLConnection) url.openConnection();
110      }
111
112      // Any cookies to attach to the request?
113      if (CollectionUtil.hasValues(inCookies))
114      {
115         StringBuilderPlus buffer = new StringBuilderPlus().setDelimiter("; ");
116         for (Cookie cookie : inCookies)
117         {
118            buffer.delimitedAppend(cookie.getName() + "=" + URLEncoder.encode(cookie.getValue(), "UTF-8"));
119         }
120
121         conn.setRequestProperty("Cookie", buffer.toString());
122      }
123
124      conn.connect();
125
126
127      int statusCode = conn.getResponseCode();
128      if (statusCode != 200)
129      {
130         String msg = null;
131         try
132         {
133            msg = StreamUtil.inputStreamToString(conn.getErrorStream());
134         }
135         catch (Exception e)
136         {
137
138         }
139         throw new IOException("Couldn't establish a connection to " + inURL + "!\nHTTP response code " + statusCode + (StringUtil.isSet(msg) ? "\n" + msg : ""));
140      }
141
142      return conn;
143   }
144
145   //---------------------------------------------------------------------------
146   public static void makeHttpsTrustEveryone()
147         throws Exception
148   {
149      X509TrustManager tooTrustingMgr = new X509TrustManager()
150      {
151         public X509Certificate[] getAcceptedIssuers()
152         {
153            return null;
154         }
155
156         public void checkClientTrusted(X509Certificate[] inCerts,
157                                        String inAuthType)
158         {
159         }
160
161         public void checkServerTrusted(X509Certificate[] inCerts,
162                                        String inAuthType)
163         {
164         }
165      };
166
167      TrustManager[] trustAllCerts = new TrustManager[] { tooTrustingMgr };
168
169      SSLContext context = SSLContext.getInstance("SSL");
170
171      HostnameVerifier hostNameVerifier = new HostnameVerifier()
172      {
173         public boolean verify(String arg0, SSLSession arg1)
174         {
175            return true;
176         }
177      };
178
179      context.init(null, trustAllCerts, new SecureRandom());
180
181      HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
182
183      HttpsURLConnection.setDefaultHostnameVerifier(hostNameVerifier);
184   }
185}