public < P > HttpURLConnection getConnection ( final String serviceUrl , final P postData , final String requestType ) throws IOException { if ( requestType == null || ! REQUEST_METHODS . contains ( requestType ) ) { throw new IllegalArgumentException ( String . format ( REQUEST_METHOD_NOT_ALLOWED , requestType ) ) ; } if ( postData == null && "POST" . equals ( requestType ) ) { throw new IllegalArgumentException ( "POST detected without a payload, please supply a payload with a POST request" ) ; } final URL restService = new URL ( serviceUrl ) ; final HttpURLConnection connection ; if ( proxy != null ) { connection = ( HttpURLConnection ) restService . openConnection ( proxy ) ; } else { connection = ( HttpURLConnection ) restService . openConnection ( ) ; } connection . setDoInput ( true ) ; connection . setRequestProperty ( "Accept" , "application/json" ) ; connection . setUseCaches ( false ) ; connection . setRequestProperty ( "charset" , "utf-8" ) ; connection . setRequestProperty ( "Connection" , "close" ) ; connection . setRequestProperty ( "Authorization" , "AccessKey " + accessKey ) ; connection . setRequestProperty ( "User-agent" , userAgentString ) ; if ( "POST" . equals ( requestType ) || "PATCH" . equals ( requestType ) ) { connection . setRequestMethod ( requestType ) ; connection . setDoOutput ( true ) ; connection . setRequestProperty ( "Content-Type" , "application/json" ) ; ObjectMapper mapper = new ObjectMapper ( ) ; mapper . setSerializationInclusion ( Include . NON_NULL ) ; // Specifically set the date format for POST requests so scheduled // messages and other things relying on specific date formats don't // fail when sending. DateFormat df = getDateFormat ( ) ; mapper . setDateFormat ( df ) ; final String json = mapper . writeValueAsString ( postData ) ; connection . getOutputStream ( ) . write ( json . getBytes ( String . valueOf ( StandardCharsets . UTF_8 ) ) ) ; } else if ( "DELETE" . equals ( requestType ) ) { // could have just used rquestType as it is connection . setDoOutput ( false ) ; connection . setRequestMethod ( "DELETE" ) ; connection . setRequestProperty ( "Content-Type" , "text/plain" ) ; } else { connection . setDoOutput ( false ) ; connection . setRequestMethod ( "GET" ) ; connection . setRequestProperty ( "Content-Type" , "text/plain" ) ; } return connection ; }
Create a HttpURLConnection connection object