尝试使用inputstream和errorstream的资源

时间:2017-02-27 01:28:34

标签: java try-with-resources

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);
}

1 个答案:

答案 0 :(得分:1)

如果我理解了您的问题,那么您可以使用三元运算符? :BufferedReader中构建try-with-resources。另外,我将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);
}