尝试使用输入流和错误流的资源

Try with resource for both inputstream and errorstream

当涉及到 getInputStreamgetErrorStream

时,如何使用 try with resource 覆盖所有角落
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
BufferedReader bufferedReader;
if(connection.getResponseCode() == 200) {
    bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
    bufferedReader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}

String line;
StringBuilder result = new StringBuilder();
while((line = bufferedReader.readLine()) != null) {result.append(line);}
bufferedReader.close();

if(connection.getResponseCode() != 200) {
    throw new Gson().fromJson(result.toString(), FooException.class);
} else {
    return new Gson().fromJson(result.toString(), Foo.class);
}

如果我理解你的问题,那么你可以使用三元运算符 ? :try-with-resources 中构造你的 BufferedReader。另外,我会将 responseCode 保存到局部变量中。像,

StringBuilder result = new StringBuilder();
int responseCode = connection.getResponseCode();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
        responseCode == 200 ? connection.getInputStream() 
        : connection.getErrorStream()))) {
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        result.append(line);
    }
}
if (responseCode != 200) {
    throw new Gson().fromJson(result.toString(), FooException.class);
} else {
    return new Gson().fromJson(result.toString(), Foo.class);
}