@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 5) {// 如果已经重试了5次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof InterruptedIOException) {// 超时 return false; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// SSL握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; }
@Before @SuppressWarnings("unchecked") public void createRestClient() throws IOException { CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class); when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer(new Answer<Future<HttpResponse>>() { @Override public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable { HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0]; HttpUriRequest request = (HttpUriRequest)requestProducer.generateRequest(); HttpHost httpHost = requestProducer.getTarget(); HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2]; assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class)); FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3]; //return the desired status code or exception depending on the path if (request.getURI().getPath().equals("/soe")) { futureCallback.failed(new SocketTimeoutException(httpHost.toString())); } else if (request.getURI().getPath().equals("/coe")) { futureCallback.failed(new ConnectTimeoutException(httpHost.toString())); } else if (request.getURI().getPath().equals("/ioe")) { futureCallback.failed(new IOException(httpHost.toString())); } else { int statusCode = Integer.parseInt(request.getURI().getPath().substring(1)); StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, ""); futureCallback.completed(new BasicHttpResponse(statusLine)); } return null; } }); int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5); httpHosts = new HttpHost[numHosts]; for (int i = 0; i < numHosts; i++) { httpHosts[i] = new HttpHost("localhost", 9200 + i); } failureListener = new HostsTrackingFailureListener(); restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener); }
@Override public Socket connectSocket( final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context ) throws IOException { Socket socket0 = socket != null ? socket : createSocket(context); if (localAddress != null) { socket0.bind(localAddress); } try { socket0.connect(remoteAddress, connectTimeout); } catch (SocketTimeoutException e) { throw new ConnectTimeoutException(e, host, remoteAddress.getAddress()); } return socket0; }
@Override public boolean retryRequest( IOException exception, int executionCount, HttpContext context) { if (executionCount > retryExecutionCount) { return false; } if (exception instanceof InterruptedIOException) { return false; } if (exception instanceof UnknownHostException) { return false; } if (exception instanceof ConnectTimeoutException) { return true; } if (exception instanceof SSLException) { return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent return true; } return false; }
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 3) {// 如果已经重试了3次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return true; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// ssl握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; }
@NonNull protected String getErrorTip(@NonNull Throwable error) { String errorTip = null; if(error == null){ return errorTip; } if(error instanceof UnknownHostException){ errorTip = getString(R.string.no_network_tip); } else if (error instanceof SocketTimeoutException || error instanceof ConnectTimeoutException) { errorTip = getString(R.string.load_timeout_tip); } else if (error instanceof HttpError) { errorTip = error.getMessage(); } else { errorTip = StringUtils.isBlank(error.getMessage()) ? error.toString() : error.getMessage(); } return errorTip; }
@Test(timeout = 60 * 1000) public void testSslHandshakeTimeout() { AmazonHttpClient httpClient = new AmazonHttpClient(new ClientConfiguration() .withSocketTimeout(CLIENT_SOCKET_TO).withMaxErrorRetry(0)); System.out.println("Sending request to localhost..."); try { httpClient.requestExecutionBuilder() .request(new EmptyHttpRequest(server.getHttpsEndpoint(), HttpMethodName.GET)) .execute(); fail("Client-side socket read timeout is expected!"); } catch (AmazonClientException e) { /** * Http client catches the SocketTimeoutException and throws a * ConnectTimeoutException. * {@link org.apache.http.impl.conn.DefaultHttpClientConnectionOperator#connect(ManagedHttpClientConnection, HttpHost, InetSocketAddress, int, SocketConfig, HttpContext)} */ Assert.assertTrue(e.getCause() instanceof ConnectTimeoutException); ConnectTimeoutException cte = (ConnectTimeoutException) e.getCause(); Assert.assertThat(cte.getMessage(), org.hamcrest.Matchers .containsString("Read timed out")); } }
/** * 根据Volley错误对象返回CommonResponse对象并写入错误信息. * * @param error Volley错误对象 * @return 返回CommonResponse对象并写入错误信息s */ private static CommonResponse getErrorCommonResponse(VolleyError error) { CommonResponse response = null; Throwable cause = error.getCause(); if (cause == null) { cause = error; } if (cause instanceof TimeoutException) { response = new CommonResponse(CodeEnum._404); } else if (cause instanceof TimeoutException) { response = new CommonResponse(CodeEnum.CONNECT_TIMEOUT); } else if (cause instanceof ConnectTimeoutException) { response = new CommonResponse(CodeEnum.CONNECT_TIMEOUT); } else if (cause instanceof TimeoutError) { response = new CommonResponse(CodeEnum.CONNECT_TIMEOUT); } else if (cause instanceof UnknownHostException) { response = new CommonResponse(CodeEnum.UNKNOWN_HOST); } else if (cause instanceof IOException) { response = new CommonResponse(CodeEnum.NETWORK_EXCEPTION); } else { response = new CommonResponse(CodeEnum.EXCEPTION.getCode(), cause.getLocalizedMessage()); } return response; }
public boolean retryRequest( IOException exception, int executionCount, HttpContext context) { if (executionCount >= 5) { // Do not retry if over max retry count return false; } if (exception instanceof InterruptedIOException) { // Timeout return false; } if (exception instanceof UnknownHostException) { // Unknown host return false; } if (exception instanceof ConnectTimeoutException) { // Connection refused return false; } if (exception instanceof SSLException) { // SSL handshake exception return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent return true; } return false; }
/** * @see SocketFactory#connectSocket(Socket, String, int, * InetAddress, int, HttpParams) */ public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
@Test public void testDelegateConnectionTimeoutException() throws Exception { doThrow(new ClientHandlerException(new ConnectTimeoutException())).when(_delegate).doIt(); TestInterface service = _serviceFactory.create(_remoteEndPoint); try { service.doIt(); } catch (PartitionForwardingException e) { assertTrue(e.getCause() instanceof ConnectTimeoutException); } assertEquals(_metricRegistry.getMeters().get("bv.emodb.web.partition-forwarding.TestInterface.errors").getCount(), 1); verify(_delegateServiceFactory).create(_remoteEndPoint); verify(_delegate).doIt(); }
/** * 根据Volley错误对象返回CommonResponse对象并写入错误信息. * * @param error Volley错误对象 * @return 返回CommonResponse对象并写入错误信息s */ private static CommonResponse getErrorCommonResponse(VolleyError error) { CommonResponse response; Throwable cause = error.getCause(); if (cause == null) { cause = error; } if (cause instanceof TimeoutException) { response = new CommonResponse(CodeEnum._404); } else if (cause instanceof ConnectTimeoutException) { response = new CommonResponse(CodeEnum.CONNECT_TIMEOUT); } else if (cause instanceof TimeoutError) { response = new CommonResponse(CodeEnum.CONNECT_TIMEOUT); } else if (cause instanceof UnknownHostException) { response = new CommonResponse(CodeEnum.UNKNOWN_HOST); } else if (cause instanceof IOException) { response = new CommonResponse(CodeEnum.NETWORK_EXCEPTION); } else { response = new CommonResponse(CodeEnum.EXCEPTION.getCode(), cause.getLocalizedMessage()); } return response; }
/** * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket, * java.lang.String, int, java.net.InetAddress, int, * org.apache.http.params.HttpParams) */ public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
@Override public Socket connectSocket( final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException, ConnectTimeoutException { Socket sock; if (socket != null) { sock = socket; } else { sock = createSocket(context); } if (localAddress != null) { sock.bind(localAddress); } try { sock.connect(remoteAddress, connectTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException(ex, host, remoteAddress.getAddress()); } return sock; }
/** * @deprecated (4.1) Use {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)} */ @Override @Deprecated public Socket connectSocket( final Socket socket, final String host, final int port, final InetAddress localAddress, final int localPort, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { InetSocketAddress local = null; if (localAddress != null || localPort > 0) { local = new InetSocketAddress(localAddress, localPort > 0 ? localPort : 0); } final InetAddress remoteAddress; if (this.nameResolver != null) { remoteAddress = this.nameResolver.resolve(host); } else { remoteAddress = InetAddress.getByName(host); } final InetSocketAddress remote = new InetSocketAddress(remoteAddress, port); return connectSocket(socket, remote, local, params); }
/** * @since 4.1 */ @Override public Socket connectSocket( final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { Args.notNull(remoteAddress, "Remote address"); Args.notNull(params, "HTTP parameters"); final HttpHost host; if (remoteAddress instanceof HttpInetSocketAddress) { host = ((HttpInetSocketAddress) remoteAddress).getHttpHost(); } else { host = new HttpHost(remoteAddress.getHostName(), remoteAddress.getPort(), "https"); } final int socketTimeout = HttpConnectionParams.getSoTimeout(params); final int connectTimeout = HttpConnectionParams.getConnectionTimeout(params); socket.setSoTimeout(socketTimeout); return connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, null); }
@Override public Socket connectSocket( final Socket socket, final String host, final int port, final InetAddress local, final int localPort, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { final InetAddress remote; if (this.nameResolver != null) { remote = this.nameResolver.resolve(host); } else { remote = InetAddress.getByName(host); } InetSocketAddress localAddress = null; if (local != null || localPort > 0) { localAddress = new InetSocketAddress(local, localPort > 0 ? localPort : 0); } final InetSocketAddress remoteAddress = new HttpInetSocketAddress( new HttpHost(host, port), remote, port); return connectSocket(socket, remoteAddress, localAddress, params); }
@Override public Socket connectSocket( final Socket sock, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { final String host = remoteAddress.getHostName(); final int port = remoteAddress.getPort(); InetAddress local = null; int localPort = 0; if (localAddress != null) { local = localAddress.getAddress(); localPort = localAddress.getPort(); } return this.factory.connectSocket(sock, host, port, local, localPort, params); }
@Override public Socket connectSocket( final int connectTimeout, final Socket sock, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException, ConnectTimeoutException { if(waitPolicy == WaitPolicy.BEFORE_CONNECT) { latch(); } final Socket socket = delegate.connectSocket( connectTimeout, sock, host, remoteAddress, localAddress, context); if(waitPolicy == WaitPolicy.AFTER_CONNECT) { latch(); } return socket; }
@Test(expected=ConnectTimeoutException.class) public void testConnectTimeout() throws Exception { final HttpContext context = new BasicHttpContext(); final HttpHost host = new HttpHost("somehost"); final InetAddress ip1 = InetAddress.getByAddress(new byte[] {10, 0, 0, 1}); final InetAddress ip2 = InetAddress.getByAddress(new byte[] {10, 0, 0, 2}); Mockito.when(dnsResolver.resolve("somehost")).thenReturn(new InetAddress[] { ip1, ip2 }); Mockito.when(socketFactoryRegistry.lookup("http")).thenReturn(plainSocketFactory); Mockito.when(schemePortResolver.resolve(host)).thenReturn(80); Mockito.when(plainSocketFactory.createSocket(Mockito.<HttpContext>any())).thenReturn(socket); Mockito.when(plainSocketFactory.connectSocket( Mockito.anyInt(), Mockito.<Socket>any(), Mockito.<HttpHost>any(), Mockito.<InetSocketAddress>any(), Mockito.<InetSocketAddress>any(), Mockito.<HttpContext>any())).thenThrow(new SocketTimeoutException()); connectionOperator.connect(conn, host, null, 1000, SocketConfig.DEFAULT, context); }
/** * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(Socket, * String, int, InetAddress, int, * HttpParams) */ public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
@Test(expected=ConnectTimeoutException.class) public void testConnectionTimeout() throws Exception { // Scenario: To emulate connection timeout, simply connect to a non-routable IP address Exception exceptionCaught = null; final int connectTimeout = 1000; // Create a non-routable URL final String url = "http://10.255.255.1:" + mockServer.getServerPort() + "/something.m3u8"; // Stop the server to simulate connection timeout mockServer.stopServer(); long start = System.currentTimeMillis(); try { PlaylistFactory.parsePlaylist(PlaylistVersion.TWELVE, new URL(url), connectTimeout, 0, 0); } catch (Exception ex) { exceptionCaught = ex; } // Verify that timeout occurred within 5 seconds (5 * connectTimeout) Assert.assertTrue(System.currentTimeMillis() - start < 5000); throw exceptionCaught; }
@NonNull public static String getReadableString(@NonNull Context context, @NonNull Exception e) { if (e instanceof ConnectTimeoutException || e instanceof SocketTimeoutException) { return context.getString(R.string.em_timeout); } else if (e instanceof UnknownHostException) { return context.getString(R.string.em_unknown_host); } else if (e instanceof ResponseCodeException) { ResponseCodeException responseCodeException = (ResponseCodeException) e; String error = context.getString(R.string.em_response_code, responseCodeException.getResponseCode()); if (responseCodeException.isIdentifiedResponseCode()) { error += ", " + responseCodeException.getMessage(); } return error; } else if (e instanceof ProtocolException && e.getMessage().startsWith("Too many follow-up requests:")) { return context.getString(R.string.em_redirection); } else if (e instanceof SocketException) { return context.getString(R.string.em_socket); } else if (e instanceof NMBException) { return e.getMessage(); } else { Say.d(TAG, "Can't recognize this Exception", e); return context.getString(R.string.em_unknown); } }
@Override public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // The following exceptions will be whitelisted, i.e.: When an exception // of this type is raised, the request will be retried. AsyncHttpClient.allowRetryExceptionClass(IOException.class); AsyncHttpClient.allowRetryExceptionClass(SocketTimeoutException.class); AsyncHttpClient.allowRetryExceptionClass(ConnectTimeoutException.class); // The following exceptions will be blacklisted, i.e.: When an exception // of this type is raised, the request will not be retried and it will // fail immediately. AsyncHttpClient.blockRetryExceptionClass(UnknownHostException.class); AsyncHttpClient.blockRetryExceptionClass(ConnectionPoolTimeoutException.class); }
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= MAX_RETRY_COUNT) { return false; } if (exception instanceof InterruptedIOException) { return false; } if (exception instanceof UnknownHostException) { return false; } if (exception instanceof ConnectTimeoutException) { return false; } if (exception instanceof SSLException) { return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); return !(request instanceof HttpEntityEnclosingRequest); }
protected static int resOf(Exception e) { if (e instanceof NoConnectionException || e instanceof ConnectException) { return R.string.exception_no_connection; } if (e instanceof ConnectTimeoutException || e instanceof SocketException || e instanceof SocketTimeoutException) { return R.string.exception_timeout; } if (e instanceof NoHttpResponseException || e instanceof FileNotFoundException || e instanceof EOFException || e instanceof UnknownHostException || e instanceof SSLException) { return R.string.exception_no_response; } if (e instanceof HttpStatusException) { return R.string.exception_http_status; } if (e instanceof ErrorCodeException) { try { String name = "exception_" + ((ErrorCodeException) e).getCode(); return R.string.class.getField(name).getInt(null); } catch (Exception ex) { return 0; } } return 0; }
public void doTask(DetailCapturerTask task, String param) { try { Integer id = task.getData(Integer.class); ComicsDetail detail = capture(id, param); reClient(); task.setResult(detail); manager.complete(task); }catch(ConnectTimeoutException to){ reClient(); manager.error(task); }catch (Throwable t) { logger.error("抓取数据出错 : param=" + param, t); reClient(); manager.error(task); } }
@Test public void exceedMaxConnectionAttempts() throws Exception { when(request.execute()).thenThrow(new ConnectTimeoutException("error")); TaxiiStatus.Feed feed = new TaxiiStatus.Feed(); when(taxiiStatusDao.find("my-collection")).thenReturn(feed); task.run(); assertThat(feed.getIoErrorCount(), is(1)); task.run(); assertThat(feed.getIoErrorCount(), is(2)); verifyLog(mockAppender, "HTTP connection problem"); assertThat(statistics.getErrors(), is(0L)); task.run(); assertThat(feed.getIoErrorCount(), is(3)); verifyLog(mockAppender, "Error"); assertThat(statistics.getErrors(), is(1L)); }
/** * @deprecated Use {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)} */ @Deprecated public Socket connectSocket( final Socket socket, final String host, int port, final InetAddress localAddress, int localPort, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { InetSocketAddress local = null; if (localAddress != null || localPort > 0) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } local = new InetSocketAddress(localAddress, localPort); } InetAddress remoteAddress; if (this.nameResolver != null) { remoteAddress = this.nameResolver.resolve(host); } else { remoteAddress = InetAddress.getByName(host); } InetSocketAddress remote = new InetSocketAddress(remoteAddress, port); return connectSocket(socket, remote, local, params); }
public HttpResponse emulateRequest(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext, RequestDirector requestDirector) throws HttpException, IOException { if (logHttpRequests) { System.out.println(" <-- " + httpRequest.getRequestLine()); } HttpResponse httpResponse = findResponse(httpRequest); if (logHttpRequests) { System.out.println(" --> " + (httpResponse == null ? null : httpResponse.getStatusLine().getStatusCode())); } if (httpResponse == null) { throw new RuntimeException("Unexpected call to execute, no pending responses are available. See Robolectric.addPendingResponse(). Request was: " + httpRequest.getRequestLine().getMethod() + " " + httpRequest.getRequestLine().getUri()); } else { HttpParams params = httpResponse.getParams(); if (HttpConnectionParams.getConnectionTimeout(params) < 0) { throw new ConnectTimeoutException("Socket is not connected"); } else if (HttpConnectionParams.getSoTimeout(params) < 0) { throw new ConnectTimeoutException("The operation timed out"); } } addRequestInfo(new HttpRequestInfo(httpRequest, httpHost, httpContext, requestDirector)); addHttpResponse(httpResponse); return httpResponse; }
@Test public void shouldSupportConnectionTimeoutWithExceptions() throws Exception { Robolectric.setDefaultHttpResponse(new TestHttpResponse() { @Override public HttpParams getParams() { HttpParams httpParams = super.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, -1); return httpParams; } }); DefaultHttpClient client = new DefaultHttpClient(); try { client.execute(new HttpGet("http://www.nowhere.org")); } catch (ConnectTimeoutException x) { return; } fail("Exception should have been thrown"); }
@Test public void shouldSupportSocketTimeoutWithExceptions() throws Exception { Robolectric.setDefaultHttpResponse(new TestHttpResponse() { @Override public HttpParams getParams() { HttpParams httpParams = super.getParams(); HttpConnectionParams.setSoTimeout(httpParams, -1); return httpParams; } }); DefaultHttpClient client = new DefaultHttpClient(); try { client.execute(new HttpGet("http://www.nowhere.org")); } catch (ConnectTimeoutException x) { return; } fail("Exception should have been thrown"); }