Skip to content

Commit 378acbd

Browse files
committed
issue #342. add a default base path configuration
1 parent a3e81e5 commit 378acbd

File tree

12 files changed

+137
-23
lines changed

12 files changed

+137
-23
lines changed

CHANGELOG.md

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
1+
## 3.7.00
2+
* Issue #342: Add a default base URL configuration
3+
14
## 3.6.01
25
* Issue #341:
36
* Do not URLDecode cookie values because they may not be and decoding can remove legit values like +
47
* Split cookie pairs on the first = only so values can have =
58

6-
## 3.4.00
9+
## 3.6.00
710
* issue #336 Add ProgressMonitor for file downloads.
811

912
## 3.5.00

docs/index.md

+13-2
Original file line numberDiff line numberDiff line change
@@ -92,12 +92,22 @@ Unirest.get("http://httpbin.org/{fruit}")
9292

9393
// Results in `http://httpbin.org/apple`
9494
```
95-
Basically the placeholder `{method}` will be replaced with `apple`.
95+
The placeholder `{fruit}` will be replaced with `apple`.
9696

97-
The placeholder's format is as easy as: `{custom_name}`
97+
The placeholder's format is as easy as wrapping in curly braces: `{custom_name}`
9898

9999
All param values will be URL-Encoded for you
100100

101+
## Default Base URLs
102+
You can configure a default base URL to be used for all requests that do not contain a full URL.
103+
104+
This configuration will result in a GET to "http://homestar.com/runner"
105+
```java
106+
Unirest.config().defaultBaseUrl("http://homestar.com");
107+
108+
Unirest.get("/runner").asString();
109+
```
110+
101111
## Query Parameters
102112
Query-string params can be built up one by one
103113

@@ -507,6 +517,7 @@ Changing Unirest's config should ideally be done once, or rarely. There are seve
507517
| ```errorHandler(Consumer<HttpResponse<?>> consumer)``` | Set a global error handler that will be invoked for any status > 400 or a parsing error | |
508518
| ```interceptor(Interceptor value)``` | Set a global Interceptor handler that will be invoked before and after each request | |
509519
| ```hostNameVerifier(HostNameVerifier value)``` | Set a custom HostNameVerifier for the security configuration | DefaultHostNameVerifier |
520+
| ```defaultBaseUrl(String value)``` | Set a default base URL to be used for all requests that do not already contain a scheme | |
510521

511522
## Global Interceptor
512523
You can set a global interceptor for your configuration. This is invoked before and after each request.

object-mapper-gson/pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<parent>
66
<groupId>com.konghq</groupId>
77
<artifactId>unirest-java-parent</artifactId>
8-
<version>3.6.02-SNAPSHOT</version>
8+
<version>3.7.00-SNAPSHOT</version>
99
</parent>
1010

1111
<artifactId>unirest-object-mappers-gson</artifactId>

object-mapper-jackson/pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<parent>
66
<groupId>com.konghq</groupId>
77
<artifactId>unirest-java-parent</artifactId>
8-
<version>3.6.02-SNAPSHOT</version>
8+
<version>3.7.00-SNAPSHOT</version>
99
</parent>
1010

1111
<artifactId>unirest-objectmapper-jackson</artifactId>

pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<groupId>com.konghq</groupId>
55
<artifactId>unirest-java-parent</artifactId>
66
<packaging>pom</packaging>
7-
<version>3.6.02-SNAPSHOT</version>
7+
<version>3.7.00-SNAPSHOT</version>
88
<name>unirest</name>
99
<description>Parent pom for unirest packages</description>
1010
<url>http://github.com/Kong/unirest-java/</url>

unirest/pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<parent>
55
<groupId>com.konghq</groupId>
66
<artifactId>unirest-java-parent</artifactId>
7-
<version>3.6.02-SNAPSHOT</version>
7+
<version>3.7.00-SNAPSHOT</version>
88
</parent>
99

1010
<description>Simplified, lightweight HTTP client library.</description>

unirest/src/main/java/kong/unirest/BaseRequest.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ abstract class BaseRequest<R extends HttpRequest> implements HttpRequest<R> {
6161
BaseRequest(Config config, HttpMethod method, String url) {
6262
this.config = config;
6363
this.method = method;
64-
this.url = new Path(url);
64+
this.url = new Path(url, config.getDefaultBaseUrl());
6565
headers.putAll(config.getDefaultHeaders());
6666
}
6767

@@ -323,7 +323,7 @@ public <T> PagedList<T> asPaged(Function<HttpRequest, HttpResponse> mappingFunct
323323
PagedList<T> all = new PagedList<>();
324324
String nextLink = this.getUrl();
325325
do {
326-
this.url = new Path(nextLink);
326+
this.url = new Path(nextLink, config.getDefaultBaseUrl());
327327
HttpResponse<T> next = mappingFunction.apply(this);
328328
all.add(next);
329329
nextLink = linkExtractor.apply(next);

unirest/src/main/java/kong/unirest/Config.java

+19-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@
4949

5050
import static kong.unirest.Util.tryCast;
5151

52-
5352
public class Config {
5453
public static final int DEFAULT_CONNECTION_TIMEOUT = 10000;
5554
public static final int DEFAULT_MAX_CONNECTIONS = 200;
@@ -86,6 +85,7 @@ public class Config {
8685
private SSLContext sslContext;
8786
private Interceptor interceptor = new DefaultInterceptor();
8887
private HostnameVerifier hostnameVerifier;
88+
private String defaultBaseUrl;
8989

9090
public Config() {
9191
setDefaults();
@@ -577,6 +577,20 @@ public Config addShutdownHook(boolean value) {
577577
return this;
578578
}
579579

580+
/**
581+
* set a default base url for all routes.
582+
* this is overridden if the url contains a valid base already
583+
* the url may contain path params
584+
*
585+
* for example. Setting a default path of 'http://somwhere'
586+
* and then calling Unirest with Unirest.get('/place')
587+
* will result in a path of 'https://somwehre/place'
588+
* @param value
589+
*/
590+
public void defaultBaseUrl(String value) {
591+
this.defaultBaseUrl = value;
592+
}
593+
580594
/**
581595
* Return default headers that are added to every request
582596
*
@@ -829,4 +843,8 @@ private Optional<DefaultInterceptor> getDefaultInterceptor() {
829843
public HostnameVerifier getHostnameVerifier() {
830844
return hostnameVerifier;
831845
}
846+
847+
String getDefaultBaseUrl() {
848+
return this.defaultBaseUrl;
849+
}
832850
}

unirest/src/main/java/kong/unirest/Path.java

+9-3
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,15 @@ class Path {
3737
private String url;
3838
private String rawPath;
3939

40-
Path(String url) {
41-
this.url = url;
42-
this.rawPath = url;
40+
Path(String url, String defaultBasePath) {
41+
if(defaultBasePath != null && url != null && !url.toLowerCase().startsWith("http")){
42+
String full = defaultBasePath + url;
43+
this.url = full;
44+
this.rawPath = full;
45+
} else {
46+
this.url = url;
47+
this.rawPath = url;
48+
}
4349
}
4450

4551
public void param(Map<String, Object> params) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* The MIT License
3+
*
4+
* Copyright for portions of unirest-java are held by Kong Inc (c) 2013.
5+
*
6+
* Permission is hereby granted, free of charge, to any person obtaining
7+
* a copy of this software and associated documentation files (the
8+
* "Software"), to deal in the Software without restriction, including
9+
* without limitation the rights to use, copy, modify, merge, publish,
10+
* distribute, sublicense, and/or sell copies of the Software, and to
11+
* permit persons to whom the Software is furnished to do so, subject to
12+
* the following conditions:
13+
*
14+
* The above copyright notice and this permission notice shall be
15+
* included in all copies or substantial portions of the Software.
16+
*
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18+
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19+
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20+
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21+
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22+
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23+
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24+
*/
25+
26+
package BehaviorTests;
27+
28+
import kong.unirest.Unirest;
29+
import org.junit.jupiter.api.Test;
30+
31+
public class BaseUrlTest extends BddTest {
32+
33+
@Test
34+
void canConfigureADefaultBaseUrl() {
35+
Unirest.config().defaultBaseUrl(MockServer.HOST);
36+
37+
Unirest.get("/get")
38+
.asObject(RequestCapture.class)
39+
.getBody()
40+
.assertUrl(MockServer.GET);
41+
}
42+
43+
@Test
44+
void willNotUseTheDefaultIfOverridden() {
45+
Unirest.config().defaultBaseUrl("http://somewhere");
46+
47+
Unirest.get(MockServer.GET)
48+
.asObject(RequestCapture.class)
49+
.getBody()
50+
.assertUrl(MockServer.GET);
51+
}
52+
53+
@Test
54+
void defaultUrlsCanHavePlaceholders() {
55+
Unirest.config().defaultBaseUrl(MockServer.PASSED_PATH_PARAM);
56+
57+
Unirest.get("/{another}")
58+
.routeParam("params", "George")
59+
.routeParam("another", "Ringo")
60+
.asObject(RequestCapture.class)
61+
.getBody()
62+
.assertUrl("http://localhost:4567/get/George/passed/Ringo");
63+
}
64+
}

unirest/src/test/java/BehaviorTests/BddTest.java

+4-2
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
import kong.unirest.*;
2929
import org.junit.After;
3030
import org.junit.Before;
31+
import org.junit.jupiter.api.AfterEach;
32+
import org.junit.jupiter.api.BeforeEach;
3133

3234
import java.io.IOException;
3335
import java.util.concurrent.CountDownLatch;
@@ -41,7 +43,7 @@ public class BddTest {
4143
private boolean status;
4244
private String fail;
4345

44-
@Before
46+
@Before @BeforeEach
4547
public void setUp() {
4648
//TestUtil.debugApache();
4749
MockServer.reset();
@@ -50,7 +52,7 @@ public void setUp() {
5052
status = false;
5153
}
5254

53-
@After
55+
@After @AfterEach
5456
public void tearDown() {
5557
Unirest.shutDown(true);
5658
}

unirest/src/test/java/kong/unirest/PathTest.java

+18-8
Original file line numberDiff line numberDiff line change
@@ -32,19 +32,19 @@
3232
public class PathTest {
3333
@Test
3434
public void pathIsTheSameIfUrlIs() {
35-
Path p = new Path("https://localhost/apples");
36-
Path o = new Path("https://localhost/apples");
35+
Path p = new Path("https://localhost/apples", null);
36+
Path o = new Path("https://localhost/apples", null);
3737
assertEquals(p, o);
3838
}
3939

4040
@Test
4141
public void pathsWithDifferentParams() {
4242
String raw = "http://somewhere/fruits/{id}";
43-
Path q = new Path(raw);
43+
Path q = new Path(raw, null);
4444
q.param("id", "apple");
45-
Path w = new Path(raw);
45+
Path w = new Path(raw, null);
4646
w.param("id", "apple");
47-
Path e = new Path(raw);
47+
Path e = new Path(raw, null);
4848
e.param("id", "oranges");
4949

5050
assertEquals(q,w);
@@ -54,14 +54,24 @@ public void pathsWithDifferentParams() {
5454
@Test
5555
public void queryParamsMatter() {
5656
String raw = "http://somewhere/fruits/}";
57-
Path q = new Path(raw);
57+
Path q = new Path(raw, null);
5858
q.queryString("id", "apple");
59-
Path w = new Path(raw);
59+
Path w = new Path(raw, null);
6060
w.queryString("id", "apple");
61-
Path e = new Path(raw);
61+
Path e = new Path(raw, null);
6262
e.queryString("id", "oranges");
6363

6464
assertEquals(q,w);
6565
assertNotEquals(q, e);
6666
}
67+
68+
@Test
69+
public void canBuildUsingDefaultBase() {
70+
assertEquals("http://somwhere/fruit", new Path("/fruit","http://somwhere").toString());
71+
}
72+
73+
@Test
74+
public void willNotAddBaseIfPrimaryPathIsFull() {
75+
assertEquals("http://somwhere/fruit", new Path("http://somwhere/fruit","http://elsewhere/rocks").toString());
76+
}
6777
}

0 commit comments

Comments
 (0)