Request { public HttpURLConnection connect() throws ConnectException { final long start = System.currentTimeMillis(); try { HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection(); connection.setUseCaches(false); connection.setDoOutput(false); connection.connect(); System.out.println(String.format("Connected with URL %s in %dms.", mUrl, (System.currentTimeMillis() - start) / 1000)); return connection; } catch (IOException e) { throw new ConnectException(new RequestException(e)); } } Request(URL url); HttpURLConnection connect();  }
@Test public void shouldDispatchRequest() throws ConnectException, IOException { Request request = new Request.RequestBuilder("host", 80, "/path") .setStreamHandler(new URLStreamHandler() { @Override protected URLConnection openConnection(final URL url) throws IOException { when(mHttpURLConnection.getInputStream()).thenReturn(new ByteArrayInputStream("{}".getBytes(Charsets.UTF_8))); return mHttpURLConnection; } }) .create(); HttpURLConnection connection = request.connect(); assertEquals("{}", CharStreams.toString(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8))); }
@Test public void shouldThrowRequestException() throws ConnectException, IOException { Request request = new Request.RequestBuilder("host", 80, "/path") .setStreamHandler(new URLStreamHandler() { @Override protected URLConnection openConnection(final URL url) throws IOException { throw new IOException(); } }) .create(); try { request.connect(); Assert.fail("Expected exception."); } catch (ConnectException exception) { assertTrue(exception.getCause() instanceof ConnectException.RequestException); } }