Check for null error stream (#2249)

This commit is contained in:
Lai Jiang 2023-12-06 13:30:37 -05:00 committed by GitHub
parent 01f868cefc
commit 4893ea307b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 0 deletions

View file

@ -50,6 +50,8 @@ public final class UrlConnectionUtils {
try (InputStream is =
responseCode < 400 ? connection.getInputStream() : connection.getErrorStream()) {
return ByteStreams.toByteArray(is);
} catch (NullPointerException e) {
return new byte[] {};
}
}

View file

@ -29,6 +29,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.List;
@ -104,4 +105,21 @@ public class UrlConnectionUtilsTest {
"Multipart data contains autogenerated boundary: "
+ "------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
}
@Test
void testErrorStream() throws Exception {
HttpsURLConnection connection = mock(HttpsURLConnection.class);
when(connection.getResponseCode()).thenReturn(400);
when(connection.getErrorStream())
.thenReturn(new ByteArrayInputStream("Failure".getBytes(UTF_8)));
assertThat(UrlConnectionUtils.getResponseBytes(connection))
.isEqualTo("Failure".getBytes(UTF_8));
}
@Test
void testErrorStream_null() throws Exception {
HttpsURLConnection connection = mock(HttpsURLConnection.class);
when(connection.getResponseCode()).thenReturn(400);
assertThat(UrlConnectionUtils.getResponseBytes(connection)).isEmpty();
}
}