String httpPost ( String url , String body , UsernamePasswordCredentials credentials ) throws Exception { logger . debug ( format ( "httpPost %s, body:%s" , url , body ) ) ; final HttpClientBuilder httpClientBuilder = HttpClientBuilder . create ( ) ; CredentialsProvider provider = null ; if ( credentials != null ) { provider = new BasicCredentialsProvider ( ) ; provider . setCredentials ( AuthScope . ANY , credentials ) ; httpClientBuilder . setDefaultCredentialsProvider ( provider ) ; } if ( registry != null ) { httpClientBuilder . setConnectionManager ( new PoolingHttpClientConnectionManager ( registry ) ) ; } HttpClient client = httpClientBuilder . build ( ) ; HttpPost httpPost = new HttpPost ( url ) ; httpPost . setConfig ( getRequestConfig ( ) ) ; AuthCache authCache = new BasicAuthCache ( ) ; HttpHost targetHost = new HttpHost ( httpPost . getURI ( ) . getHost ( ) , httpPost . getURI ( ) . getPort ( ) ) ; if ( credentials != null ) { authCache . put ( targetHost , new BasicScheme ( ) ) ; } final HttpClientContext context = HttpClientContext . create ( ) ; if ( null != provider ) { context . setCredentialsProvider ( provider ) ; } if ( credentials != null ) { context . setAuthCache ( authCache ) ; } httpPost . setEntity ( new StringEntity ( body ) ) ; if ( credentials != null ) { httpPost . addHeader ( new BasicScheme ( ) . authenticate ( credentials , httpPost , context ) ) ; } HttpResponse response = client . execute ( httpPost , context ) ; int status = response . getStatusLine ( ) . getStatusCode ( ) ; HttpEntity entity = response . getEntity ( ) ; logger . trace ( format ( "httpPost %s sending..." , url ) ) ; String responseBody = entity != null ? EntityUtils . toString ( entity ) : null ; logger . trace ( format ( "httpPost %s responseBody %s" , url , responseBody ) ) ; if ( status >= 400 ) { Exception e = new Exception ( format ( "POST request to %s with request body: %s, " + "failed with status code: %d. Response: %s" , url , body , status , responseBody ) ) ; logger . error ( e . getMessage ( ) ) ; throw e ; } logger . debug ( format ( "httpPost Status: %d returning: %s " , status , responseBody ) ) ; return responseBody ; }
Http Post Request .