You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@solr.apache.org by ge...@apache.org on 2024/02/01 14:32:16 UTC

(solr) branch main updated: SOLR-17066: Switch HttpSolrClient away from coreURLs, pt 2 (#2231)

This is an automated email from the ASF dual-hosted git repository.

gerlowskija pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/solr.git


The following commit(s) were added to refs/heads/main by this push:
     new 5c64979cd91 SOLR-17066: Switch HttpSolrClient away from coreURLs, pt 2 (#2231)
5c64979cd91 is described below

commit 5c64979cd911a5d8295d37ebf5b2a4a6ac1ba1df
Author: Jason Gerlowski <ge...@apache.org>
AuthorDate: Thu Feb 1 09:32:10 2024 -0500

    SOLR-17066: Switch HttpSolrClient away from coreURLs, pt 2 (#2231)
    
    Providing a core URL as a SolrClient's "base URL" prevents it from
    communicating with other cores or making core-agnostic API requests
    (e.g. node healthcheck, list cores, etc.)
    
    This commit migrates usage in solr-core tests, solrj, solrj-streaming,
    hadoop-auth, and hdfs to use the `withDefaultCollection` builder
    method in lieu of using core-based URLs directly.
---
 .../client/solrj/impl/ConnectionReuseTest.java     |  3 +-
 .../apache/solr/cloud/LeaderTragicEventTest.java   | 11 +++--
 .../test/org/apache/solr/cloud/RouteFieldTest.java | 20 +++++---
 .../cloud/TestLeaderElectionWithEmptyReplica.java  |  3 +-
 .../org/apache/solr/cloud/TestPullReplica.java     | 15 ++++--
 .../apache/solr/cloud/TestRandomFlRTGCloud.java    |  2 +-
 .../solr/cloud/TestRandomRequestDistribution.java  | 10 ++--
 .../org/apache/solr/cloud/TestTlogReplica.java     | 15 ++++--
 .../solr/cloud/api/collections/ShardSplitTest.java |  3 +-
 .../apache/solr/handler/ReplicationTestHelper.java | 12 +++++
 .../handler/TestHealthCheckHandlerLegacyMode.java  |  4 +-
 .../solr/handler/TestReplicationHandler.java       | 56 ++++++++++------------
 .../TestReplicationHandlerDiskOverFlow.java        |  8 +---
 .../solr/handler/admin/CoreAdminHandlerTest.java   | 15 ++++--
 .../DistributedQueryElevationComponentTest.java    |  3 +-
 .../solr/handler/component/SearchHandlerTest.java  | 13 +++--
 .../src/test/org/apache/solr/pkg/TestPackages.java | 10 ++++
 .../solr/update/DeleteByIdWithRouterFieldTest.java |  5 +-
 .../hadoop/TestImpersonationWithHadoopAuth.java    |  3 +-
 .../TestSolrCloudWithSecureImpersonation.java      |  3 +-
 .../org/apache/solr/hdfs/cloud/StressHdfsTest.java |  3 +-
 .../solr/client/solrj/io/SolrClientCache.java      | 27 +++++++++--
 .../solrj/impl/ConcurrentUpdateSolrClient.java     | 14 +++++-
 .../solr/client/solrj/impl/LBHttpSolrClient.java   | 15 ++++--
 .../java/org/apache/solr/common/util/URLUtil.java  | 15 ++++++
 .../solr/client/solrj/SolrExampleTestsBase.java    |  2 +-
 26 files changed, 200 insertions(+), 90 deletions(-)

diff --git a/solr/core/src/test/org/apache/solr/client/solrj/impl/ConnectionReuseTest.java b/solr/core/src/test/org/apache/solr/client/solrj/impl/ConnectionReuseTest.java
index e68ea8722bf..20965ef6cb6 100644
--- a/solr/core/src/test/org/apache/solr/client/solrj/impl/ConnectionReuseTest.java
+++ b/solr/core/src/test/org/apache/solr/client/solrj/impl/ConnectionReuseTest.java
@@ -89,7 +89,8 @@ public class ConnectionReuseTest extends SolrCloudTestCase {
             .withThreadCount(1)
             .build();
       case 1:
-        return new HttpSolrClient.Builder(url.toString() + "/" + COLLECTION)
+        return new HttpSolrClient.Builder(url.toString())
+            .withDefaultCollection(COLLECTION)
             .withHttpClient(httpClient)
             .build();
       case 2:
diff --git a/solr/core/src/test/org/apache/solr/cloud/LeaderTragicEventTest.java b/solr/core/src/test/org/apache/solr/cloud/LeaderTragicEventTest.java
index b2c3e6eab6d..a1453f07cc2 100644
--- a/solr/core/src/test/org/apache/solr/cloud/LeaderTragicEventTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/LeaderTragicEventTest.java
@@ -113,7 +113,10 @@ public class LeaderTragicEventTest extends SolrCloudTestCase {
     // Check that we can continue indexing after this
     updateResponse = new UpdateRequest().add("id", "2").commit(cluster.getSolrClient(), collection);
     assertEquals(0, updateResponse.getStatus());
-    try (SolrClient followerClient = new HttpSolrClient.Builder(oldLeader.getCoreUrl()).build()) {
+    try (SolrClient followerClient =
+        new HttpSolrClient.Builder(oldLeader.getBaseUrl())
+            .withDefaultCollection(oldLeader.getCoreName())
+            .build()) {
       QueryResponse queryResponse = new QueryRequest(new SolrQuery("*:*")).process(followerClient);
       assertEquals(
           queryResponse.getResults().toString(), 2, queryResponse.getResults().getNumFound());
@@ -128,9 +131,9 @@ public class LeaderTragicEventTest extends SolrCloudTestCase {
       Replica oldLeader = dc.getLeader("shard1");
       log.info("Will crash leader : {}", oldLeader);
 
-      try (SolrClient solrClient =
-          new HttpSolrClient.Builder(dc.getLeader("shard1").getCoreUrl()).build()) {
-        new UpdateRequest().add("id", "99").commit(solrClient, null);
+      final Replica leaderReplica = dc.getLeader("shard1");
+      try (SolrClient solrClient = new HttpSolrClient.Builder(leaderReplica.getBaseUrl()).build()) {
+        new UpdateRequest().add("id", "99").commit(solrClient, leaderReplica.getCoreName());
         fail("Should have injected tragedy");
       } catch (RemoteSolrException e) {
         // solrClient.add would throw RemoteSolrException with code 500
diff --git a/solr/core/src/test/org/apache/solr/cloud/RouteFieldTest.java b/solr/core/src/test/org/apache/solr/cloud/RouteFieldTest.java
index 3884f14134d..22afebb4fb3 100644
--- a/solr/core/src/test/org/apache/solr/cloud/RouteFieldTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/RouteFieldTest.java
@@ -38,6 +38,7 @@ import org.apache.solr.common.cloud.Replica;
 import org.apache.solr.common.cloud.ZkStateReader;
 import org.apache.solr.common.params.CommonParams;
 import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.URLUtil;
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.slf4j.Logger;
@@ -154,13 +155,8 @@ public class RouteFieldTest extends SolrCloudTestCase {
     params.add(CommonParams.SORT, "sorter asc");
     params.add(CommonParams.ROWS, "1000");
 
-    SolrClient solrClient = new HttpSolrClient.Builder(urlId).build();
-    SolrDocumentList docsId = (SolrDocumentList) solrClient.request(request).get("response");
-    solrClient.close();
-
-    solrClient = new HttpSolrClient.Builder(urlRoute).build();
-    SolrDocumentList docsRoute = (SolrDocumentList) solrClient.request(request).get("response");
-    solrClient.close();
+    final var docsId = getDocsMatching(urlId, request);
+    final var docsRoute = getDocsMatching(urlRoute, request);
 
     assertEquals(
         "We should have the exact same number of docs on each shard",
@@ -175,4 +171,14 @@ public class RouteFieldTest extends SolrCloudTestCase {
           idRoute - 1_500_000);
     }
   }
+
+  private SolrDocumentList getDocsMatching(String coreUrl, QueryRequest request)
+      throws IOException, SolrServerException {
+    final var baseUrl = URLUtil.extractBaseUrl(coreUrl);
+    final var coreName = URLUtil.extractCoreFromCoreUrl(coreUrl);
+    try (SolrClient solrClient =
+        new HttpSolrClient.Builder(baseUrl).withDefaultCollection(coreName).build()) {
+      return (SolrDocumentList) solrClient.request(request).get("response");
+    }
+  }
 }
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestLeaderElectionWithEmptyReplica.java b/solr/core/src/test/org/apache/solr/cloud/TestLeaderElectionWithEmptyReplica.java
index 97df978bd10..5bab0e126b9 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestLeaderElectionWithEmptyReplica.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestLeaderElectionWithEmptyReplica.java
@@ -118,7 +118,8 @@ public class TestLeaderElectionWithEmptyReplica extends SolrCloudTestCase {
     int count = 0;
     for (Replica replica : shard.getReplicas()) {
       SolrClient client =
-          new Builder(replica.getCoreUrl())
+          new Builder(replica.getBaseUrl())
+              .withDefaultCollection(replica.getCoreName())
               .withHttpClient(((CloudLegacySolrClient) cloudClient).getHttpClient())
               .build();
       QueryResponse response = client.query(new SolrQuery("q", "*:*", "distrib", "false"));
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java b/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java
index a5b0ee21781..fd6d6eb7742 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java
@@ -464,7 +464,10 @@ public class TestPullReplica extends SolrCloudTestCase {
     List<String> ids = new ArrayList<>(slice.getReplicas().size());
     for (Replica rAdd : slice.getReplicas()) {
       try (SolrClient client =
-          new HttpSolrClient.Builder(rAdd.getCoreUrl()).withHttpClient(httpClient).build()) {
+          new HttpSolrClient.Builder(rAdd.getBaseUrl())
+              .withDefaultCollection(rAdd.getCoreName())
+              .withHttpClient(httpClient)
+              .build()) {
         client.add(new SolrInputDocument("id", String.valueOf(id), "foo_s", "bar"));
       }
       SolrDocument docCloudClient =
@@ -472,7 +475,10 @@ public class TestPullReplica extends SolrCloudTestCase {
       assertEquals("bar", docCloudClient.getFieldValue("foo_s"));
       for (Replica rGet : slice.getReplicas()) {
         try (SolrClient client =
-            new HttpSolrClient.Builder(rGet.getCoreUrl()).withHttpClient(httpClient).build()) {
+            new HttpSolrClient.Builder(rGet.getBaseUrl())
+                .withDefaultCollection(rGet.getCoreName())
+                .withHttpClient(httpClient)
+                .build()) {
           SolrDocument doc = client.getById(String.valueOf(id));
           assertEquals("bar", doc.getFieldValue("foo_s"));
         }
@@ -483,7 +489,10 @@ public class TestPullReplica extends SolrCloudTestCase {
     SolrDocumentList previousAllIdsResult = null;
     for (Replica rAdd : slice.getReplicas()) {
       try (SolrClient client =
-          new HttpSolrClient.Builder(rAdd.getCoreUrl()).withHttpClient(httpClient).build()) {
+          new HttpSolrClient.Builder(rAdd.getBaseUrl())
+              .withDefaultCollection(rAdd.getCoreName())
+              .withHttpClient(httpClient)
+              .build()) {
         SolrDocumentList allIdsResult = client.getById(ids);
         if (previousAllIdsResult != null) {
           assertTrue(compareSolrDocumentList(previousAllIdsResult, allIdsResult));
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestRandomFlRTGCloud.java b/solr/core/src/test/org/apache/solr/cloud/TestRandomFlRTGCloud.java
index 29115f29196..26c0797407e 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestRandomFlRTGCloud.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestRandomFlRTGCloud.java
@@ -435,7 +435,7 @@ public class TestRandomFlRTGCloud extends SolrCloudTestCase {
   /** Helper to convert from wt string parameter to actual SolrClient. */
   private static SolrClient getSolrClient(final String jettyBaseUrl, final String wt) {
     HttpSolrClient.Builder builder =
-        new HttpSolrClient.Builder(jettyBaseUrl + "/" + COLLECTION_NAME + "/");
+        new HttpSolrClient.Builder(jettyBaseUrl).withDefaultCollection(COLLECTION_NAME);
     switch (wt) {
       case "xml":
         builder.withResponseParser(RAW_XML_RESPONSE_PARSER);
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestRandomRequestDistribution.java b/solr/core/src/test/org/apache/solr/cloud/TestRandomRequestDistribution.java
index 768f258cc50..9bf2777975e 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestRandomRequestDistribution.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestRandomRequestDistribution.java
@@ -110,7 +110,8 @@ public class TestRandomRequestDistribution extends AbstractFullDistribZkTestBase
     String baseUrl = replicas.iterator().next().getBaseUrl();
     if (!baseUrl.endsWith("/")) baseUrl += "/";
     try (SolrClient client =
-        new HttpSolrClient.Builder(baseUrl + "a1x2")
+        new HttpSolrClient.Builder(baseUrl)
+            .withDefaultCollection("a1x2")
             .withConnectionTimeout(2000, TimeUnit.MILLISECONDS)
             .withSocketTimeout(5000, TimeUnit.MILLISECONDS)
             .build()) {
@@ -221,11 +222,10 @@ public class TestRandomRequestDistribution extends AbstractFullDistribZkTestBase
     // Query against the node which hosts the down replica
 
     String baseUrl = notLeader.getBaseUrl();
-    if (!baseUrl.endsWith("/")) baseUrl += "/";
-    String path = baseUrl + "football";
-    log.info("Firing queries against path={}", path);
+    log.info("Firing queries against path={} and collection=football", baseUrl);
     try (SolrClient client =
-        new HttpSolrClient.Builder(path)
+        new HttpSolrClient.Builder(baseUrl)
+            .withDefaultCollection("football")
             .withConnectionTimeout(2000, TimeUnit.MILLISECONDS)
             .withSocketTimeout(5000, TimeUnit.MILLISECONDS)
             .build()) {
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestTlogReplica.java b/solr/core/src/test/org/apache/solr/cloud/TestTlogReplica.java
index 937b8f1fe17..c3baa8e5486 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestTlogReplica.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestTlogReplica.java
@@ -406,7 +406,10 @@ public class TestTlogReplica extends SolrCloudTestCase {
     List<String> ids = new ArrayList<>(slice.getReplicas().size());
     for (Replica rAdd : slice.getReplicas()) {
       try (SolrClient client =
-          new HttpSolrClient.Builder(rAdd.getCoreUrl()).withHttpClient(httpClient).build()) {
+          new HttpSolrClient.Builder(rAdd.getBaseUrl())
+              .withDefaultCollection(rAdd.getCoreName())
+              .withHttpClient(httpClient)
+              .build()) {
         client.add(new SolrInputDocument("id", String.valueOf(id), "foo_s", "bar"));
       }
       SolrDocument docCloudClient =
@@ -415,7 +418,10 @@ public class TestTlogReplica extends SolrCloudTestCase {
       assertEquals("bar", docCloudClient.getFieldValue("foo_s"));
       for (Replica rGet : slice.getReplicas()) {
         try (SolrClient client =
-            new HttpSolrClient.Builder(rGet.getCoreUrl()).withHttpClient(httpClient).build()) {
+            new HttpSolrClient.Builder(rGet.getBaseUrl())
+                .withDefaultCollection(rGet.getCoreName())
+                .withHttpClient(httpClient)
+                .build()) {
           SolrDocument doc = client.getById(String.valueOf(id));
           assertEquals("bar", doc.getFieldValue("foo_s"));
         }
@@ -426,7 +432,10 @@ public class TestTlogReplica extends SolrCloudTestCase {
     SolrDocumentList previousAllIdsResult = null;
     for (Replica rAdd : slice.getReplicas()) {
       try (SolrClient client =
-          new HttpSolrClient.Builder(rAdd.getCoreUrl()).withHttpClient(httpClient).build()) {
+          new HttpSolrClient.Builder(rAdd.getBaseUrl())
+              .withDefaultCollection(rAdd.getCoreName())
+              .withHttpClient(httpClient)
+              .build()) {
         SolrDocumentList allIdsResult = client.getById(ids);
         if (previousAllIdsResult != null) {
           assertTrue(compareSolrDocumentList(previousAllIdsResult, allIdsResult));
diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/ShardSplitTest.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/ShardSplitTest.java
index f252c23e901..3794840112a 100644
--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/ShardSplitTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/ShardSplitTest.java
@@ -307,7 +307,8 @@ public class ShardSplitTest extends BasicDistributedZkTest {
     int count = 0;
     for (Replica replica : shard.getReplicas()) {
       var client =
-          new HttpSolrClient.Builder(replica.getCoreUrl())
+          new HttpSolrClient.Builder(replica.getBaseUrl())
+              .withDefaultCollection(replica.getCoreName())
               .withHttpClient(((CloudLegacySolrClient) cloudClient).getHttpClient())
               .build();
       QueryResponse response = client.query(new SolrQuery("q", "*:*", "distrib", "false"));
diff --git a/solr/core/src/test/org/apache/solr/handler/ReplicationTestHelper.java b/solr/core/src/test/org/apache/solr/handler/ReplicationTestHelper.java
index bb6a06c16cd..892dc679d3f 100644
--- a/solr/core/src/test/org/apache/solr/handler/ReplicationTestHelper.java
+++ b/solr/core/src/test/org/apache/solr/handler/ReplicationTestHelper.java
@@ -64,8 +64,20 @@ public final class ReplicationTestHelper {
     return jetty;
   }
 
+  /**
+   * @param baseUrl the root URL for a Solr node
+   */
   public static SolrClient createNewSolrClient(String baseUrl) {
+    return createNewSolrClient(baseUrl, null);
+  }
+
+  /**
+   * @param baseUrl the root URL for a Solr node
+   * @param collectionOrCore an optional default collection/core for the created client
+   */
+  public static SolrClient createNewSolrClient(String baseUrl, String collectionOrCore) {
     return new HttpSolrClient.Builder(baseUrl)
+        .withDefaultCollection(collectionOrCore)
         .withConnectionTimeout(15000, TimeUnit.MILLISECONDS)
         .withSocketTimeout(90000, TimeUnit.MILLISECONDS)
         .build();
diff --git a/solr/core/src/test/org/apache/solr/handler/TestHealthCheckHandlerLegacyMode.java b/solr/core/src/test/org/apache/solr/handler/TestHealthCheckHandlerLegacyMode.java
index c5a4ba0be25..b376e52bd9b 100644
--- a/solr/core/src/test/org/apache/solr/handler/TestHealthCheckHandlerLegacyMode.java
+++ b/solr/core/src/test/org/apache/solr/handler/TestHealthCheckHandlerLegacyMode.java
@@ -60,7 +60,7 @@ public class TestHealthCheckHandlerLegacyMode extends SolrTestCaseJ4 {
     leaderJetty = ReplicationTestHelper.createAndStartJetty(leader);
     leaderClient =
         ReplicationTestHelper.createNewSolrClient(
-            buildUrl(leaderJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+            buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
     leaderClientHealthCheck =
         ReplicationTestHelper.createNewSolrClient(buildUrl(leaderJetty.getLocalPort()));
 
@@ -71,7 +71,7 @@ public class TestHealthCheckHandlerLegacyMode extends SolrTestCaseJ4 {
     followerJetty = createAndStartJetty(follower);
     followerClient =
         ReplicationTestHelper.createNewSolrClient(
-            buildUrl(followerJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+            buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
     followerClientHealthCheck =
         ReplicationTestHelper.createNewSolrClient(buildUrl(followerJetty.getLocalPort()));
 
diff --git a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java
index 730b326f30f..eeb0c360523 100644
--- a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java
+++ b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java
@@ -123,7 +123,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
     leaderJetty = createAndStartJetty(leader);
     leaderClient =
         ReplicationTestHelper.createNewSolrClient(
-            buildUrl(leaderJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+            buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     follower =
         new SolrInstance(
@@ -132,7 +132,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
     followerJetty = createAndStartJetty(follower);
     followerClient =
         ReplicationTestHelper.createNewSolrClient(
-            buildUrl(followerJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+            buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     System.setProperty("solr.indexfetcher.sotimeout2", "45000");
   }
@@ -300,10 +300,10 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
     leaderClient.close();
     leaderClient =
         ReplicationTestHelper.createNewSolrClient(
-            buildUrl(leaderJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+            buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
     followerClient =
         ReplicationTestHelper.createNewSolrClient(
-            buildUrl(followerJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+            buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     clearIndexWithReplication();
     {
@@ -373,7 +373,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
       repeaterJetty = createAndStartJetty(repeater);
       repeaterClient =
           ReplicationTestHelper.createNewSolrClient(
-              buildUrl(repeaterJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+              buildUrl(repeaterJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
       NamedList<Object> details = getDetails(repeaterClient);
 
@@ -407,7 +407,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
       instanceJetty = createAndStartJetty(solrInstance);
       client =
           ReplicationTestHelper.createNewSolrClient(
-              buildUrl(instanceJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+              buildUrl(instanceJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
       NamedList<Object> details = getDetails(client);
 
@@ -566,8 +566,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
 
     leaderJetty = createAndStartJetty(leader);
     leaderClient.close();
-    leaderClient =
-        createNewSolrClient(buildUrl(leaderJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+    leaderClient = createNewSolrClient(buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     follower.setTestPort(leaderJetty.getLocalPort());
     follower.copyConfigFile(follower.getSolrConfigFile(), "solrconfig.xml");
@@ -587,7 +586,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
     followerJetty = createAndStartJetty(follower);
     followerClient.close();
     followerClient =
-        createNewSolrClient(buildUrl(followerJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+        createNewSolrClient(buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
     // add a doc with new field and commit on leader to trigger index fetch from follower.
     index(leaderClient, "id", "2000", "name", "name = " + 2000, "newname", "newname = " + 2000);
     leaderClient.commit();
@@ -674,7 +673,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
       // close and re-create leader client because its connection pool has stale connections
       leaderClient.close();
       leaderClient =
-          createNewSolrClient(buildUrl(leaderJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+          createNewSolrClient(buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
       nDocs--;
       for (int i = 0; i < nDocs; i++) index(leaderClient, "id", i, "name", "name = " + i);
@@ -810,7 +809,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
     followerClient.close();
     followerClient =
         ReplicationTestHelper.createNewSolrClient(
-            buildUrl(followerJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+            buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     leaderClient.deleteByQuery("*:*");
     followerClient.deleteByQuery("*:*");
@@ -959,14 +958,14 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
       followerJetty = createAndStartJetty(follower);
       followerClient.close();
       followerClient =
-          createNewSolrClient(buildUrl(followerJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+          createNewSolrClient(buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
       leader.copyConfigFile(CONF_DIR + "solrconfig-leader3.xml", "solrconfig.xml");
       leaderJetty.stop();
       leaderJetty = createAndStartJetty(leader);
       leaderClient.close();
       leaderClient =
-          createNewSolrClient(buildUrl(leaderJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+          createNewSolrClient(buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
       leaderClient.deleteByQuery("*:*");
       followerClient.deleteByQuery("*:*");
@@ -1112,7 +1111,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
     followerJetty = createAndStartJetty(follower);
     followerClient.close();
     followerClient =
-        createNewSolrClient(buildUrl(followerJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+        createNewSolrClient(buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     try {
       repeater =
@@ -1125,7 +1124,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
         repeaterClient.close();
       }
       repeaterClient =
-          createNewSolrClient(buildUrl(repeaterJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+          createNewSolrClient(buildUrl(repeaterJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
       for (int i = 0; i < 3; i++) index(leaderClient, "id", i, "name", "name = " + i);
 
@@ -1193,8 +1192,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
 
     leaderJetty = createAndStartJetty(leader);
     leaderClient.close();
-    leaderClient =
-        createNewSolrClient(buildUrl(leaderJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+    leaderClient = createNewSolrClient(buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     for (int i = 0; i < nDocs; i++) index(leaderClient, "id", i, "name", "name = " + i);
 
@@ -1211,7 +1209,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
     followerJetty = createAndStartJetty(follower);
     followerClient.close();
     followerClient =
-        createNewSolrClient(buildUrl(followerJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+        createNewSolrClient(buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     // get docs from follower and check if number is equal to leader
     NamedList<Object> followerQueryRsp = rQuery(nDocs, "*:*", followerClient);
@@ -1245,7 +1243,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
       leaderJetty = createAndStartJetty(leader);
       leaderClient.close();
       leaderClient =
-          createNewSolrClient(buildUrl(leaderJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+          createNewSolrClient(buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
       for (int i = 0; i < nDocs; i++) index(leaderClient, "id", i, "name", "name = " + i);
 
@@ -1270,7 +1268,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
       followerJetty = createAndStartJetty(follower);
       followerClient.close();
       followerClient =
-          createNewSolrClient(buildUrl(followerJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+          createNewSolrClient(buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
       // get docs from follower and check if number is equal to leader
       NamedList<Object> followerQueryRsp = rQuery(nDocs, "*:*", followerClient);
@@ -1301,8 +1299,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
 
     leaderJetty = createAndStartJetty(leader);
     leaderClient.close();
-    leaderClient =
-        createNewSolrClient(buildUrl(leaderJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+    leaderClient = createNewSolrClient(buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     leaderClient.deleteByQuery("*:*");
     for (int i = 0; i < docs; i++) index(leaderClient, "id", i, "name", "name = " + i);
@@ -1320,7 +1317,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
     followerJetty = createAndStartJetty(follower);
     followerClient.close();
     followerClient =
-        createNewSolrClient(buildUrl(followerJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+        createNewSolrClient(buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     // get docs from follower and check if number is equal to leader
     NamedList<Object> followerQueryRsp = rQuery(docs, "*:*", followerClient);
@@ -1397,8 +1394,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
 
     leaderJetty = createAndStartJetty(leader);
     leaderClient.close();
-    leaderClient =
-        createNewSolrClient(buildUrl(leaderJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+    leaderClient = createNewSolrClient(buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     follower.setTestPort(leaderJetty.getLocalPort());
     follower.copyConfigFile(follower.getSolrConfigFile(), "solrconfig.xml");
@@ -1407,7 +1403,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
     followerJetty = createAndStartJetty(follower);
     followerClient.close();
     followerClient =
-        createNewSolrClient(buildUrl(followerJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+        createNewSolrClient(buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     followerClient.deleteByQuery("*:*");
     followerClient.commit();
@@ -1453,8 +1449,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
     useFactory(null);
     leaderJetty = createAndStartJetty(leader);
     leaderClient.close();
-    leaderClient =
-        createNewSolrClient(buildUrl(leaderJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+    leaderClient = createNewSolrClient(buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     // index docs
     final int totalDocs = TestUtil.nextInt(random(), 17, 53);
@@ -1481,8 +1476,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
     // Start again and replicate the data
     useFactory(null);
     leaderJetty = createAndStartJetty(leader);
-    leaderClient =
-        createNewSolrClient(buildUrl(leaderJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+    leaderClient = createNewSolrClient(buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     // start follower
     follower.setTestPort(leaderJetty.getLocalPort());
@@ -1490,7 +1484,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
     followerJetty = createAndStartJetty(follower);
     followerClient.close();
     followerClient =
-        createNewSolrClient(buildUrl(followerJetty.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME);
+        createNewSolrClient(buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     long startTime = System.nanoTime();
 
diff --git a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandlerDiskOverFlow.java b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandlerDiskOverFlow.java
index 9b35aa29cf5..c66a1dd7201 100644
--- a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandlerDiskOverFlow.java
+++ b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandlerDiskOverFlow.java
@@ -81,9 +81,7 @@ public class TestReplicationHandlerDiskOverFlow extends SolrTestCaseJ4 {
     leaderJetty = createAndStartJetty(leader);
     leaderClient =
         ReplicationTestHelper.createNewSolrClient(
-            TestReplicationHandler.buildUrl(leaderJetty.getLocalPort())
-                + "/"
-                + DEFAULT_TEST_CORENAME);
+            TestReplicationHandler.buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
     System.setProperty(TEST_URL_ALLOW_LIST, leaderJetty.getBaseUrl().toString());
 
     follower =
@@ -93,9 +91,7 @@ public class TestReplicationHandlerDiskOverFlow extends SolrTestCaseJ4 {
     followerJetty = createAndStartJetty(follower);
     followerClient =
         ReplicationTestHelper.createNewSolrClient(
-            TestReplicationHandler.buildUrl(followerJetty.getLocalPort())
-                + "/"
-                + DEFAULT_TEST_CORENAME);
+            TestReplicationHandler.buildUrl(followerJetty.getLocalPort()), DEFAULT_TEST_CORENAME);
 
     System.setProperty("solr.indexfetcher.sotimeout2", "45000");
   }
diff --git a/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java
index f1a76a8efe6..68a31ca6879 100644
--- a/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java
@@ -305,7 +305,8 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
     runner.start();
 
     try (SolrClient client =
-        new HttpSolrClient.Builder(runner.getBaseUrl() + "/corex")
+        new HttpSolrClient.Builder(runner.getBaseUrl().toString())
+            .withDefaultCollection("corex")
             .withConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
             .withSocketTimeout(DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
             .build()) {
@@ -377,7 +378,8 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
     runner.start();
 
     try (SolrClient client =
-        new HttpSolrClient.Builder(runner.getBaseUrl() + "/corex")
+        new HttpSolrClient.Builder(runner.getBaseUrl().toString())
+            .withDefaultCollection("corex")
             .withConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
             .withSocketTimeout(DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
             .build()) {
@@ -388,7 +390,8 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
     }
 
     try (SolrClient client =
-        new HttpSolrClient.Builder(runner.getBaseUrl() + "/corex")
+        new HttpSolrClient.Builder(runner.getBaseUrl().toString())
+            .withDefaultCollection("corex")
             .withConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
             .withSocketTimeout(DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
             .build()) {
@@ -412,7 +415,8 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
             BaseHttpSolrClient.RemoteSolrException.class,
             () -> {
               try (SolrClient client =
-                  new HttpSolrClient.Builder(runner.getBaseUrl() + "/corex")
+                  new HttpSolrClient.Builder(runner.getBaseUrl().toString())
+                      .withDefaultCollection("corex")
                       .withConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
                       .withSocketTimeout(DEFAULT_CONNECTION_TIMEOUT * 1000, TimeUnit.MILLISECONDS)
                       .build()) {
@@ -438,7 +442,8 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
     runner.start();
 
     try (SolrClient client =
-        new HttpSolrClient.Builder(runner.getBaseUrl() + "/corex")
+        new HttpSolrClient.Builder(runner.getBaseUrl().toString())
+            .withDefaultCollection("corex")
             .withConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
             .withSocketTimeout(DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
             .build()) {
diff --git a/solr/core/src/test/org/apache/solr/handler/component/DistributedQueryElevationComponentTest.java b/solr/core/src/test/org/apache/solr/handler/component/DistributedQueryElevationComponentTest.java
index a27b6a6d3a7..4136090d6bf 100644
--- a/solr/core/src/test/org/apache/solr/handler/component/DistributedQueryElevationComponentTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/component/DistributedQueryElevationComponentTest.java
@@ -166,9 +166,10 @@ public class DistributedQueryElevationComponentTest extends BaseDistributedSearc
     assertEquals(true, document.getFieldValue("[elevated]"));
 
     // Force javabin format
-    final String clientUrl = jettys.get(0).getBaseUrl() + "/" + "collection1";
+    final String clientUrl = jettys.get(0).getBaseUrl().toString();
     try (SolrClient client =
         new HttpSolrClient.Builder(clientUrl)
+            .withDefaultCollection("collection1")
             .withResponseParser(new BinaryResponseParser())
             .build(); ) {
       SolrQuery solrQuery =
diff --git a/solr/core/src/test/org/apache/solr/handler/component/SearchHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/component/SearchHandlerTest.java
index 752e4e21c57..df69c08ce88 100644
--- a/solr/core/src/test/org/apache/solr/handler/component/SearchHandlerTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/component/SearchHandlerTest.java
@@ -157,7 +157,10 @@ public class SearchHandlerTest extends SolrTestCaseJ4 {
       Replica replica = getRandomEntry(slice.getReplicas());
       JettySolrRunner jetty = miniCluster.getReplicaJetty(replica);
       // Use the replica's core URL to avoid ZK communication
-      try (SolrClient client = new HttpSolrClient.Builder(replica.getCoreUrl()).build()) {
+      try (SolrClient client =
+          new HttpSolrClient.Builder(replica.getBaseUrl())
+              .withDefaultCollection(replica.getCoreName())
+              .build()) {
         jetty.getCoreContainer().getZkController().getZkClient().close();
         rsp = req.process(client);
         assertFalse(rsp.getResponseHeader().getBooleanArg("zkConnected"));
@@ -205,7 +208,9 @@ public class SearchHandlerTest extends SolrTestCaseJ4 {
       JettySolrRunner disconnectedJetty = miniCluster.getReplicaJetty(disconnectedReplica);
       // Use the replica's core URL to avoid ZK communication
       try (SolrClient solrClient =
-          new HttpSolrClient.Builder(disconnectedReplica.getCoreUrl()).build()) {
+          new HttpSolrClient.Builder(disconnectedReplica.getBaseUrl())
+              .withDefaultCollection(disconnectedReplica.getCoreName())
+              .build()) {
         ignoreException("ZooKeeper is not connected");
         disconnectedJetty.getCoreContainer().getZkController().getZkClient().close();
         req.process(solrClient);
@@ -262,7 +267,9 @@ public class SearchHandlerTest extends SolrTestCaseJ4 {
       }
       Replica connectedReplica = connectedSlice.getReplicas().iterator().next();
       try (SolrClient solrClient =
-          new HttpSolrClient.Builder(connectedReplica.getCoreUrl()).build()) {
+          new HttpSolrClient.Builder(connectedReplica.getBaseUrl())
+              .withDefaultCollection(connectedReplica.getCoreName())
+              .build()) {
         ignoreException("ZooKeeper is not connected");
         ignoreException("no active servers hosting shard:");
         JettySolrRunner disconnectedJetty = miniCluster.getReplicaJetty(disconnectedReplica);
diff --git a/solr/core/src/test/org/apache/solr/pkg/TestPackages.java b/solr/core/src/test/org/apache/solr/pkg/TestPackages.java
index a3f1917473d..d70aa372737 100644
--- a/solr/core/src/test/org/apache/solr/pkg/TestPackages.java
+++ b/solr/core/src/test/org/apache/solr/pkg/TestPackages.java
@@ -440,6 +440,11 @@ public class TestPackages extends SolrCloudTestCase {
         return new RequestWriter.StringPayloadContentWriter(
             "{set:{PKG_VERSIONS:{mypkg : '1.1'}}}", ClientUtils.TEXT_JSON);
       }
+
+      @Override
+      public boolean requiresCollection() {
+        return true;
+      }
     }.process(cluster.getSolrClient());
 
     add.version = "2.1";
@@ -464,6 +469,11 @@ public class TestPackages extends SolrCloudTestCase {
         return new RequestWriter.StringPayloadContentWriter(
             "{set:{PKG_VERSIONS:{mypkg : '2.1'}}}", ClientUtils.TEXT_JSON);
       }
+
+      @Override
+      public boolean requiresCollection() {
+        return true;
+      }
     }.process(cluster.getSolrClient());
 
     // now, let's force every collection using 'mypkg' to refresh
diff --git a/solr/core/src/test/org/apache/solr/update/DeleteByIdWithRouterFieldTest.java b/solr/core/src/test/org/apache/solr/update/DeleteByIdWithRouterFieldTest.java
index df32ef6783b..e4339f045eb 100644
--- a/solr/core/src/test/org/apache/solr/update/DeleteByIdWithRouterFieldTest.java
+++ b/solr/core/src/test/org/apache/solr/update/DeleteByIdWithRouterFieldTest.java
@@ -81,7 +81,10 @@ public class DeleteByIdWithRouterFieldTest extends SolrCloudTestCase {
 
     ClusterState clusterState = cluster.getSolrClient().getClusterState();
     for (Replica replica : clusterState.getCollection(COLL).getReplicas()) {
-      clients.add(new HttpSolrClient.Builder(replica.getCoreUrl()).build());
+      clients.add(
+          new HttpSolrClient.Builder(replica.getBaseUrl())
+              .withDefaultCollection(replica.getCoreName())
+              .build());
     }
   }
 
diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestImpersonationWithHadoopAuth.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestImpersonationWithHadoopAuth.java
index f9172efb9f3..a1eb218d609 100644
--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestImpersonationWithHadoopAuth.java
+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestImpersonationWithHadoopAuth.java
@@ -211,7 +211,8 @@ public class TestImpersonationWithHadoopAuth extends SolrCloudTestCase {
     // try a command to each node, one of them must be forwarded
     for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {
       try (SolrClient client =
-          new HttpSolrClient.Builder(jetty.getBaseUrl().toString() + "/" + collectionName)
+          new HttpSolrClient.Builder(jetty.getBaseUrl().toString())
+              .withDefaultCollection(collectionName)
               .build()) {
         ModifiableSolrParams params = new ModifiableSolrParams();
         params.set("q", "*:*");
diff --git a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithSecureImpersonation.java b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithSecureImpersonation.java
index 1aa4ccd425b..a7a1652cf32 100644
--- a/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithSecureImpersonation.java
+++ b/solr/modules/hadoop-auth/src/test/org/apache/solr/security/hadoop/TestSolrCloudWithSecureImpersonation.java
@@ -340,7 +340,8 @@ public class TestSolrCloudWithSecureImpersonation extends SolrTestCaseJ4 {
     // try a command to each node, one of them must be forwarded
     for (JettySolrRunner jetty : miniCluster.getJettySolrRunners()) {
       try (HttpSolrClient client =
-          new HttpSolrClient.Builder(jetty.getBaseUrl().toString() + "/" + collectionName)
+          new HttpSolrClient.Builder(jetty.getBaseUrl().toString())
+              .withDefaultCollection(collectionName)
               .build()) {
         ModifiableSolrParams params = new ModifiableSolrParams();
         params.set("q", "*:*");
diff --git a/solr/modules/hdfs/src/test/org/apache/solr/hdfs/cloud/StressHdfsTest.java b/solr/modules/hdfs/src/test/org/apache/solr/hdfs/cloud/StressHdfsTest.java
index 65ddfefa556..72acd6f5343 100644
--- a/solr/modules/hdfs/src/test/org/apache/solr/hdfs/cloud/StressHdfsTest.java
+++ b/solr/modules/hdfs/src/test/org/apache/solr/hdfs/cloud/StressHdfsTest.java
@@ -189,7 +189,8 @@ public class StressHdfsTest extends AbstractBasicDistributedZkTestBase {
     int i = 0;
     for (SolrClient client : clients) {
       try (SolrClient c =
-          new HttpSolrClient.Builder(getBaseUrl(client) + "/" + DELETE_DATA_DIR_COLLECTION)
+          new HttpSolrClient.Builder(getBaseUrl(client))
+              .withDefaultCollection(DELETE_DATA_DIR_COLLECTION)
               .withConnectionTimeout(30000, TimeUnit.MILLISECONDS)
               .build()) {
         int docCnt = random().nextInt(1000) + 1;
diff --git a/solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/SolrClientCache.java b/solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/SolrClientCache.java
index 915d9fbafc7..fdb61ee3eb1 100644
--- a/solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/SolrClientCache.java
+++ b/solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/SolrClientCache.java
@@ -37,6 +37,7 @@ import org.apache.solr.client.solrj.impl.HttpSolrClient;
 import org.apache.solr.client.solrj.impl.SolrClientBuilder;
 import org.apache.solr.common.AlreadyClosedException;
 import org.apache.solr.common.util.IOUtils;
+import org.apache.solr.common.util.URLUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -144,6 +145,14 @@ public class SolrClientCache implements Closeable {
     return client;
   }
 
+  /**
+   * Create (and cache) a SolrClient based around the provided URL
+   *
+   * @param baseUrl a Solr URL. May be either a "base" URL (i.e. ending in "/solr"), or point to a
+   *     particular collection or core.
+   * @return a SolrClient configured to use the provided URL. The cache retains a reference to the
+   *     returned client, and will close it when callers invoke {@link SolrClientCache#close()}
+   */
   public synchronized SolrClient getHttpSolrClient(String baseUrl) {
     ensureOpen();
     Objects.requireNonNull(baseUrl, "Url cannot be null!");
@@ -161,8 +170,12 @@ public class SolrClientCache implements Closeable {
   }
 
   @Deprecated
-  private static SolrClient newHttpSolrClient(String baseUrl, HttpClient httpClient) {
-    HttpSolrClient.Builder builder = new HttpSolrClient.Builder(baseUrl);
+  private static SolrClient newHttpSolrClient(String url, HttpClient httpClient) {
+    final var builder =
+        (URLUtil.isBaseUrl(url))
+            ? new HttpSolrClient.Builder(url)
+            : new HttpSolrClient.Builder(URLUtil.extractBaseUrl(url))
+                .withDefaultCollection(URLUtil.extractCoreFromCoreUrl(url));
     adjustTimeouts(builder, httpClient);
     return builder.build();
   }
@@ -177,10 +190,14 @@ public class SolrClientCache implements Closeable {
   }
 
   private static Http2SolrClient.Builder newHttp2SolrClientBuilder(
-      String baseUrl, Http2SolrClient http2SolrClient) {
-    var builder = new Http2SolrClient.Builder(baseUrl);
+      String url, Http2SolrClient http2SolrClient) {
+    final var builder =
+        (url == null || URLUtil.isBaseUrl(url)) // URL may be null here and set by caller
+            ? new Http2SolrClient.Builder(url)
+            : new Http2SolrClient.Builder(URLUtil.extractBaseUrl(url))
+                .withDefaultCollection(URLUtil.extractCoreFromCoreUrl(url));
     if (http2SolrClient != null) {
-      builder = builder.withHttpClient(http2SolrClient);
+      builder.withHttpClient(http2SolrClient);
     }
     long idleTimeout = minSocketTimeout;
     if (builder.getIdleTimeoutMillis() != null) {
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/ConcurrentUpdateSolrClient.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/ConcurrentUpdateSolrClient.java
index 1a8517211b5..5a4a129769c 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/ConcurrentUpdateSolrClient.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/ConcurrentUpdateSolrClient.java
@@ -52,6 +52,7 @@ import org.apache.solr.common.util.ExecutorUtil;
 import org.apache.solr.common.util.IOUtils;
 import org.apache.solr.common.util.NamedList;
 import org.apache.solr.common.util.SolrNamedThreadFactory;
+import org.apache.solr.common.util.URLUtil;
 import org.apache.solr.common.util.Utils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -100,8 +101,13 @@ public class ConcurrentUpdateSolrClient extends SolrClient {
    */
   protected ConcurrentUpdateSolrClient(Builder builder) {
     this.internalHttpClient = (builder.httpClient == null);
+    final var httpSolrClientBuilder =
+        (URLUtil.isBaseUrl(builder.baseSolrUrl))
+            ? new HttpSolrClient.Builder(builder.baseSolrUrl)
+            : new HttpSolrClient.Builder(URLUtil.extractBaseUrl(builder.baseSolrUrl))
+                .withDefaultCollection(URLUtil.extractCoreFromCoreUrl(builder.baseSolrUrl));
     this.client =
-        new HttpSolrClient.Builder(builder.baseSolrUrl)
+        httpSolrClientBuilder
             .withHttpClient(builder.httpClient)
             .withConnectionTimeout(builder.connectionTimeoutMillis, TimeUnit.MILLISECONDS)
             .withSocketTimeout(builder.socketTimeoutMillis, TimeUnit.MILLISECONDS)
@@ -317,7 +323,11 @@ public class ConcurrentUpdateSolrClient extends SolrClient {
           requestParams.set(CommonParams.VERSION, client.parser.getVersion());
 
           String basePath = client.getBaseURL();
-          if (update.getCollection() != null) basePath += "/" + update.getCollection();
+          if (update.getCollection() != null) {
+            basePath += "/" + update.getCollection();
+          } else if (client.getDefaultCollection() != null) {
+            basePath += "/" + client.getDefaultCollection();
+          }
 
           method = new HttpPost(basePath + "/update" + requestParams.toQueryString());
 
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/LBHttpSolrClient.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/LBHttpSolrClient.java
index 923d651afb3..b6b5c51707f 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/LBHttpSolrClient.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/LBHttpSolrClient.java
@@ -25,6 +25,7 @@ import java.util.concurrent.TimeUnit;
 import org.apache.http.client.HttpClient;
 import org.apache.solr.client.solrj.SolrClient;
 import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.URLUtil;
 
 /**
  * LBHttpSolrClient or "LoadBalanced HttpSolrClient" is a load balancing wrapper around {@link
@@ -134,10 +135,16 @@ public class LBHttpSolrClient extends LBSolrClient {
         client = httpSolrClientBuilder.build();
       }
     } else {
-      final HttpSolrClient.Builder clientBuilder =
-          new HttpSolrClient.Builder(server).withHttpClient(httpClient).withResponseParser(parser);
-      clientBuilder.withConnectionTimeout(connectionTimeoutMillis, TimeUnit.MILLISECONDS);
-      clientBuilder.withSocketTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS);
+      final var clientBuilder =
+          (URLUtil.isBaseUrl(server))
+              ? new HttpSolrClient.Builder(server)
+              : new HttpSolrClient.Builder(URLUtil.extractBaseUrl(server))
+                  .withDefaultCollection(URLUtil.extractCoreFromCoreUrl(server));
+      clientBuilder
+          .withHttpClient(httpClient)
+          .withResponseParser(parser)
+          .withConnectionTimeout(connectionTimeoutMillis, TimeUnit.MILLISECONDS)
+          .withSocketTimeout(soTimeoutMillis, TimeUnit.MILLISECONDS);
       if (requestWriter != null) {
         clientBuilder.withRequestWriter(requestWriter);
       }
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/URLUtil.java b/solr/solrj/src/java/org/apache/solr/common/util/URLUtil.java
index 026c9a959a6..78de07ba5b3 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/URLUtil.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/URLUtil.java
@@ -16,10 +16,14 @@
  */
 package org.apache.solr.common.util;
 
+import java.lang.invoke.MethodHandles;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class URLUtil {
+  private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
   public static final Pattern URL_PREFIX = Pattern.compile("^([a-z]*?://).*");
 
@@ -46,6 +50,11 @@ public class URLUtil {
     return null;
   }
 
+  public static boolean isBaseUrl(String url) {
+    final var normalizedUrl = removeTrailingSlashIfPresent(url);
+    return normalizedUrl.endsWith("/solr");
+  }
+
   /**
    * @param coreUrl a URL pointing to a specific "core" or collection (i.e. that adheres loosely to
    *     the form "scheme://host:port/solr/coreName")
@@ -55,6 +64,12 @@ public class URLUtil {
     coreUrl = removeTrailingSlashIfPresent(coreUrl);
 
     // Remove the core name and return
+    final var indexOfLastSlash = coreUrl.lastIndexOf("/");
+    if (indexOfLastSlash == -1) {
+      log.warn(
+          "Solr core URL [{}] did not contain expected path segments when parsing, ignoring...");
+      return coreUrl;
+    }
     return coreUrl.substring(0, coreUrl.lastIndexOf("/"));
   }
 
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTestsBase.java b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTestsBase.java
index 88d454cfe52..01b0940f357 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTestsBase.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTestsBase.java
@@ -64,7 +64,7 @@ public abstract class SolrExampleTestsBase extends SolrJettyTestBase {
    */
   @Override
   public SolrClient createNewSolrClient() {
-    return getHttpSolrClient(getCoreUrl());
+    return getHttpSolrClient(getBaseUrl(), DEFAULT_TEST_CORENAME);
   }
 
   /** query the example */