package com.mindprod.http;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import static java.lang.System.out;
/**
* Reads HTTP page with a generic http: https: file: etc, arbitrary URL.
*
* @author Roedy Green, Canadian Mind Products
* @version 2.3 2010-11-14 new method setInstanceFollowRedirects
* @since 1998
*/
@SuppressWarnings( { "WeakerAccess" } )
public final class Fetch extends Http
{
/**
* constructor
*/
public Fetch()
{
}
/**
* Read a message given an URL. Does not support getResponseCode or getResponseMessage.
*
* @param url complete URL including any parms, pre-encoded (use Http.encodeParms).
* might be http: https: file: and possibly others.
* @param defaultCharSet default encoding of the byte stream result, usually UTF-8 or or ISO-8859-1.
*
* @return host's response with headers and embedded length fields stripped.
* @see com.mindprod.filetransfer.Download
*/
@SuppressWarnings( { "UnusedAssignment", "MethodNamesDifferingOnlyByCase" } )
public String send( final URL url, final Charset defaultCharSet )
{
try
{
responseCode = DEFAULT_RESPONSE_CODE;
responseMessage = DEFAULT_RESPONSE_MESSAGE;
this.url = url;
final URLConnection urlc = url.openConnection();
urlc.setAllowUserInteraction( false );
urlc.setDoInput( true );
urlc.setDoOutput( false );// nothing beyond original request
urlc.setUseCaches( false );
setStandardProperties( urlc );
urlc.connect();
int estimatedLength = urlc.getContentLength();
if ( estimatedLength < 0 )
{
estimatedLength = Http.DEFAULT_LENGTH;
}
final InputStream is = urlc.getInputStream();
final String contentType = urlc.getContentType();
final Charset charSet = guessCharSet( contentType, defaultCharSet );
final boolean gzipped = "gzip".equals( urlc.getContentEncoding() )
|| "x-gzip".equals( urlc.getContentEncoding() );
String result = Read.readStringBlocking( is,
estimatedLength,
gzipped,
charSet );
if ( DEBUGGING )
{
out.println( "--------------------------------" );
out.println( "ContentType:" + contentType );
out.println( "CharSet:" + charSet );
out.println( "ContentEncoding:" + urlc.getContentEncoding() );
out.println( "Result:" + ( result == null ? "null" : result.substring( 0,
Math.min( result.length(), 300 ) ) ) );
}
is.close();
return result;
}
catch ( IOException e )
{
return null;
}
}
}