Commit aec394a6 by nobodyiam

refactor httputil error stream handling

parent f9cb281d
...@@ -8,6 +8,7 @@ import com.google.common.base.Function; ...@@ -8,6 +8,7 @@ import com.google.common.base.Function;
import com.google.common.io.CharStreams; import com.google.common.io.CharStreams;
import com.google.gson.Gson; import com.google.gson.Gson;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
...@@ -93,20 +94,33 @@ public class HttpUtil { ...@@ -93,20 +94,33 @@ public class HttpUtil {
conn.connect(); conn.connect();
statusCode = conn.getResponseCode(); statusCode = conn.getResponseCode();
String response;
try { try {
isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
} catch (Exception e) { response = CharStreams.toString(isr);
// ignore } catch (IOException ex) {
} /**
try { * according to https://docs.oracle.com/javase/7/docs/technotes/guides/net/http-keepalive.html,
esr = new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8); * we should clean up the connection by reading the response body so that the connection
} catch (Exception e) { * could be reused.
// ignore */
InputStream errorStream = conn.getErrorStream();
if (errorStream != null) {
esr = new InputStreamReader(errorStream, StandardCharsets.UTF_8);
try {
CharStreams.toString(esr);
} catch (IOException ioe) {
//ignore
}
}
throw ex;
} }
if (statusCode == 200) { if (statusCode == 200) {
String content = CharStreams.toString(isr); return new HttpResponse<>(statusCode, serializeFunction.apply(response));
return new HttpResponse<>(statusCode, serializeFunction.apply(content));
} }
if (statusCode == 304) { if (statusCode == 304) {
...@@ -117,20 +131,18 @@ public class HttpUtil { ...@@ -117,20 +131,18 @@ public class HttpUtil {
} finally { } finally {
if (isr != null) { if (isr != null) {
try { try {
CharStreams.toString(isr);
isr.close(); isr.close();
} catch (IOException e) { } catch (IOException ex) {
// ignore // ignore
} }
} }
if (esr != null) { if (esr != null) {
try { try {
CharStreams.toString(esr); esr.close();
esr.close(); } catch (IOException ex) {
} catch (Exception e) { // ignore
// ignore }
}
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment