001package votorola.g.net; // Copyright 2010-2011, Michael Allan.  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Votorola Software"), to deal in the Votorola Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicence, and/or sell copies of the Votorola Software, and to permit persons to whom the Votorola Software is furnished to do so, subject to the following conditions: The preceding copyright notice and this permission notice shall be included in all copies or substantial portions of the Votorola Software. THE VOTOROLA SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE VOTOROLA SOFTWARE OR THE USE OR OTHER DEALINGS IN THE VOTOROLA SOFTWARE.
002
003import java.io.*;
004import java.net.*;
005import votorola.g.lang.*;
006
007
008/** URLConnection utilities.
009  *
010  *     @see <a href='http://stackoverflow.com/questions/2793150'
011  *      >How to use java.net.URLConnection to fire and handle HTTP requests?</a>
012  */
013public @ThreadSafe final class URLConnectionX
014{
015
016    private URLConnectionX() {}
017
018
019
020    /** Same as connector.{@linkplain URLConnection#connect() connect}(), but wraps any
021      * ConnectException in a more informative IOException.
022      */
023    public static void connect( final URLConnection connector ) throws IOException
024    {
025        try { connector.connect(); }
026        catch( ConnectException x )
027        {
028            throw new IOException( "Unable to reach URL " + connector.getURL(), x ); // add more info
029        }
030    }
031
032
033
034    /** Sets the Cookie header in the connector preparatory to making a connection.  Reads
035      * the existing {@linkplain URLConnection#getRequestProperties() request headers}, so
036      * be sure to set them <em>before</em> calling.
037      */
038    public static void setRequestCookies( final URI uri, final URLConnection connector,
039      final CookieHandler cookieHandler ) throws IOException
040    {
041        final String headerValue = CookieHandlerX.newRequestHeader( uri,
042          connector.getRequestProperties(), cookieHandler );
043        if( headerValue != null ) connector.setRequestProperty( "Cookie", headerValue );
044    }
045
046
047}