Skip to content

Commit 81dfadc

Browse files
Brian Bohlrstoyanchev
authored andcommitted
Fix StringIndexOutOfBoundsException in RestTemplate.doExecute IOException handler when query string is an empty string
1 parent 26284ca commit 81dfadc

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

spring-web/src/main/java/org/springframework/web/client/RestTemplate.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -708,7 +708,7 @@ protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable Reques
708708
catch (IOException ex) {
709709
String resource = url.toString();
710710
String query = url.getRawQuery();
711-
resource = (query != null ? resource.substring(0, resource.indexOf(query) - 1) : resource);
711+
resource = (query != null ? resource.substring(0, resource.indexOf('?')) : resource);
712712
throw new ResourceAccessException("I/O error on " + method.name() +
713713
" request for \"" + resource + "\": " + ex.getMessage(), ex);
714714
}

spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -729,6 +729,32 @@ public void ioException() throws Exception {
729729
ex.getMessage());
730730
}
731731
}
732+
733+
@Test
734+
public void ioExceptionWithEmptyQueryString() throws Exception {
735+
736+
String scheme = "http";
737+
String authority = "example.com";
738+
String path = "/resource";
739+
URI uri = new URI(scheme, authority, path, "", null); // http://example.com/resource?
740+
741+
given(converter.canRead(String.class, null)).willReturn(true);
742+
MediaType mediaType = new MediaType("foo", "bar");
743+
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(mediaType));
744+
given(requestFactory.createRequest(uri, HttpMethod.GET)).willReturn(request);
745+
given(request.getHeaders()).willReturn(new HttpHeaders());
746+
given(request.execute()).willThrow(new IOException("Socket failure"));
747+
748+
try {
749+
template.getForObject(uri, String.class);
750+
fail("RestClientException expected");
751+
}
752+
catch (ResourceAccessException ex) {
753+
assertEquals("I/O error on GET request for \"http://example.com/resource\": " +
754+
"Socket failure; nested exception is java.io.IOException: Socket failure",
755+
ex.getMessage());
756+
}
757+
}
732758

733759
@Test
734760
public void exchange() throws Exception {

0 commit comments

Comments
 (0)