private < T > T execute ( String url , Class < T > returnType , Object requestObject ) throws Exception { URLConnection connection = new URL ( url ) . openConnection ( ) ; if ( ! ( connection instanceof HttpURLConnection ) ) { throw new IllegalStateException ( "Not an http connection! " + connection ) ; } HttpURLConnection httpConnection = ( HttpURLConnection ) connection ; httpConnection . setUseCaches ( false ) ; httpConnection . setDefaultUseCaches ( false ) ; httpConnection . setDoInput ( true ) ; /* * With followRedirects enabled, simple URL redirects work as expected. But with port redirects (http->https) * followRedirects doesn't work and a HTTP 302 code is returned instead (ARQ-1365). * * In order to handle all redirects in one place, followRedirects is set to false and all HTTP 302 response codes are * treated accordingly within the execute method. */ httpConnection . setInstanceFollowRedirects ( false ) ; try { if ( requestObject != null ) { httpConnection . setRequestMethod ( "POST" ) ; httpConnection . setDoOutput ( true ) ; httpConnection . setRequestProperty ( "Content-Type" , "application/octet-stream" ) ; } if ( requestObject != null ) { ObjectOutputStream ous = new ObjectOutputStream ( httpConnection . getOutputStream ( ) ) ; try { ous . writeObject ( requestObject ) ; } catch ( Exception e ) { throw new RuntimeException ( "Error sending request Object, " + requestObject , e ) ; } finally { ous . flush ( ) ; ous . close ( ) ; } } try { httpConnection . getResponseCode ( ) ; } catch ( ConnectException e ) { return null ; // Could not connect } if ( httpConnection . getResponseCode ( ) == HttpURLConnection . HTTP_OK ) { ObjectInputStream ois = new ObjectInputStream ( httpConnection . getInputStream ( ) ) ; Object o ; try { o = ois . readObject ( ) ; } finally { ois . close ( ) ; } if ( ! returnType . isInstance ( o ) ) { throw new IllegalStateException ( "Error reading results, expected a " + returnType . getName ( ) + " but got " + o ) ; } return returnType . cast ( o ) ; } else if ( httpConnection . getResponseCode ( ) == HttpURLConnection . HTTP_NO_CONTENT ) { return null ; } else if ( httpConnection . getResponseCode ( ) == HttpURLConnection . HTTP_MOVED_TEMP ) { String redirectUrl = httpConnection . getHeaderField ( "Location" ) ; return execute ( redirectUrl , returnType , requestObject ) ; } else if ( httpConnection . getResponseCode ( ) != HttpURLConnection . HTTP_NOT_FOUND ) { throw new IllegalStateException ( "Error launching test at " + url + ". " + "Got " + httpConnection . getResponseCode ( ) + " (" + httpConnection . getResponseMessage ( ) + ")" ) ; } } finally { httpConnection . disconnect ( ) ; } return null ; }
Executes the request to the remote url