public static URI rewriteURI(
            final URI uri,
            final HttpHost target,
            final boolean dropFragment) throws URISyntaxException {
        Args.notNull(uri, "URI");
        if (uri.isOpaque()) {
            return uri;
        }
        final URIBuilder uribuilder = new URIBuilder(uri);
        if (target != null) {
            uribuilder.setScheme(target.getSchemeName());
            uribuilder.setHost(target.getHostName());
            uribuilder.setPort(target.getPort());
        } else {
            uribuilder.setScheme(null);
            uribuilder.setHost((String) null);
            uribuilder.setPort(-1);
        }
        if (dropFragment) {
            uribuilder.setFragment(null);
        }
        final List<String> originalPathSegments = uribuilder.getPathSegments();
        final List<String> pathSegments = new ArrayList<>(originalPathSegments);
        for (final Iterator<String> it = pathSegments.iterator(); it.hasNext(); ) {
            final String pathSegment = it.next();
            if (pathSegment.isEmpty() && it.hasNext()) {
                it.remove();
            }
        }
        if (pathSegments.size() != originalPathSegments.size()) {
            uribuilder.setPathSegments(pathSegments);
        }
        if (pathSegments.isEmpty()) {
            uribuilder.setPathSegments("");
        }
        return uribuilder.build();
    }
A convenience method for creating a new {@link URI} whose scheme, host
and port are taken from the target host, but whose path, query and
fragment are taken from the existing URI. The fragment is only used if
dropFragment is false. The path is set to "/" if not explicitly specified.

@param uri
           Contains the path, query and fragment to use.
@param target
           Contains the scheme, host and port to use.
@param dropFragment
           True if the fragment should not be copied.

@throws URISyntaxException
            If the resulting URI is invalid.
ngrinder-runtime/src/main/java/org/apache/hc/client5/http/utils/URIUtils.java