Skip to content

Commit

Permalink
Fix leak in HttpService (#1325)
Browse files Browse the repository at this point in the history
* Fix deprecated ResponseBody.create() method call

By suffling parameters.

* Replace deprecated BufferedSource.buffer() call

With BufferedSource.getBuffer()

* Close okhttp3.Response with a try/resource block
  • Loading branch information
kare authored Jan 6, 2021
1 parent 7c2bba4 commit cd3ca72
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
28 changes: 15 additions & 13 deletions core/src/main/java/org/web3j/protocol/http/HttpService.java
Original file line number Diff line number Diff line change
Expand Up @@ -157,20 +157,22 @@ protected InputStream performIO(String request) throws IOException {
okhttp3.Request httpRequest =
new okhttp3.Request.Builder().url(url).headers(headers).post(requestBody).build();

okhttp3.Response response = httpClient.newCall(httpRequest).execute();
processHeaders(response.headers());
ResponseBody responseBody = response.body();
if (response.isSuccessful()) {
if (responseBody != null) {
return buildInputStream(responseBody);
try (okhttp3.Response response = httpClient.newCall(httpRequest).execute()) {
processHeaders(response.headers());
ResponseBody responseBody = response.body();
if (response.isSuccessful()) {
if (responseBody != null) {
return buildInputStream(responseBody);
} else {
return null;
}
} else {
return null;
}
} else {
int code = response.code();
String text = responseBody == null ? "N/A" : responseBody.string();
int code = response.code();
String text = responseBody == null ? "N/A" : responseBody.string();

throw new ClientConnectionException("Invalid response received: " + code + "; " + text);
throw new ClientConnectionException(
"Invalid response received: " + code + "; " + text);
}
}
}

Expand All @@ -187,7 +189,7 @@ private InputStream buildInputStream(ResponseBody responseBody) throws IOExcepti

BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body
Buffer buffer = source.buffer();
Buffer buffer = source.getBuffer();

long size = buffer.size();
if (size > Integer.MAX_VALUE) {
Expand Down
2 changes: 1 addition & 1 deletion core/src/test/java/org/web3j/protocol/ResponseTester.java
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public okhttp3.Response intercept(Chain chain) throws IOException {

okhttp3.Response response =
new okhttp3.Response.Builder()
.body(ResponseBody.create(JSON_MEDIA_TYPE, jsonResponse))
.body(ResponseBody.create(jsonResponse, JSON_MEDIA_TYPE))
.request(chain.request())
.protocol(Protocol.HTTP_2)
.code(200)
Expand Down

0 comments on commit cd3ca72

Please sign in to comment.