Fix OkHttp connection leaks on connection error

When request fails, entire response needs to be wrapped in try with
resources in order to close the connection properly and not only
response body.

Signed-off-by: Tomas Slusny <slusnucky@gmail.com>
This commit is contained in:
Tomas Slusny
2017-12-22 02:05:28 +01:00
parent a6fde8fb28
commit 4660bb3739
9 changed files with 77 additions and 104 deletions

View File

@@ -45,7 +45,6 @@ import net.runelite.http.api.item.SearchResult;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -487,16 +486,14 @@ public class ItemService
private <T> T fetchJson(Request request, Class<T> clazz) throws IOException
{
Response response = RuneliteAPI.CLIENT.newCall(request).execute();
if (!response.isSuccessful())
try (Response response = RuneliteAPI.CLIENT.newCall(request).execute())
{
throw new IOException("Unsuccessful http response: " + response.message());
}
if (!response.isSuccessful())
{
throw new IOException("Unsuccessful http response: " + response.message());
}
try (ResponseBody body = response.body())
{
InputStream in = body.byteStream();
InputStream in = response.body().byteStream();
return RuneliteAPI.GSON.fromJson(new InputStreamReader(in), clazz);
}
catch (JsonParseException ex)
@@ -513,16 +510,14 @@ public class ItemService
.url(httpUrl)
.build();
Response response = RuneliteAPI.CLIENT.newCall(request).execute();
if (!response.isSuccessful())
try (Response response = RuneliteAPI.CLIENT.newCall(request).execute())
{
throw new IOException("Unsuccessful http response: " + response.message());
}
if (!response.isSuccessful())
{
throw new IOException("Unsuccessful http response: " + response.message());
}
try (ResponseBody body = response.body())
{
return body.bytes();
return response.body().bytes();
}
}
}