@@ -43,12 +43,12 @@ public class ScannerHttpClient {
4343 private static final String EXCEPTION_MESSAGE_MISSING_SLASH = "URL path must start with slash: %s" ;
4444
4545
46- private OkHttpClient httpClient ;
46+ private OkHttpClient sharedHttpClient ;
4747 private HttpConfig httpConfig ;
4848
4949 public void init (HttpConfig httpConfig ) {
5050 this .httpConfig = httpConfig ;
51- this .httpClient = OkHttpClientFactory .create (httpConfig );
51+ this .sharedHttpClient = OkHttpClientFactory .create (httpConfig );
5252 }
5353
5454
@@ -82,9 +82,6 @@ public void downloadFromExternalUrl(String url, Path toFile) throws IOException
8282 * @throws IllegalStateException if HTTP response code is different than 2xx
8383 */
8484 private void downloadFile (String url , Path toFile , boolean authentication ) throws IOException {
85- if (httpClient == null ) {
86- throw new IllegalStateException ("ServerConnection must be initialized" );
87- }
8885 LOG .debug ("Download {} to {}" , url , toFile .toAbsolutePath ());
8986
9087 try (ResponseBody responseBody = callUrl (url , authentication , "application/octet-stream" );
@@ -120,9 +117,6 @@ public String callWebApi(String urlPath) throws IOException {
120117 * @throws IllegalStateException if HTTP response code is different than 2xx
121118 */
122119 private String callApi (String url ) throws IOException {
123- if (httpClient == null ) {
124- throw new IllegalStateException ("ServerConnection must be initialized" );
125- }
126120 try (ResponseBody responseBody = callUrl (url , true , null )) {
127121 return responseBody .string ();
128122 }
@@ -141,12 +135,21 @@ private ResponseBody callUrl(String url, boolean authentication, @Nullable Strin
141135 .get ()
142136 .url (url )
143137 .addHeader ("User-Agent" , httpConfig .getUserAgent ());
138+ OkHttpClient httpClient ;
144139 if (authentication ) {
145- if (httpConfig .getToken () != null ) {
146- requestBuilder .header ("Authorization" , "Bearer " + httpConfig .getToken ());
147- } else if (httpConfig .getLogin () != null ) {
148- requestBuilder .header ("Authorization" , Credentials .basic (httpConfig .getLogin (), httpConfig .getPassword () != null ? httpConfig .getPassword () : "" ));
149- }
140+ httpClient = sharedHttpClient .newBuilder ()
141+ .addNetworkInterceptor (chain -> {
142+ Request request = chain .request ();
143+ if (httpConfig .getToken () != null ) {
144+ request = request .newBuilder ().header ("Authorization" , "Bearer " + httpConfig .getToken ()).build ();
145+ } else if (httpConfig .getLogin () != null ) {
146+ request = request .newBuilder ().header ("Authorization" , Credentials .basic (httpConfig .getLogin (), httpConfig .getPassword () != null ? httpConfig .getPassword () : "" )).build ();
147+ }
148+ return chain .proceed (request );
149+ })
150+ .build ();
151+ } else {
152+ httpClient = sharedHttpClient ;
150153 }
151154 if (acceptHeader != null ) {
152155 requestBuilder .header ("Accept" , acceptHeader );
0 commit comments