List of usage examples for com.squareup.okhttp OkHttpClient setReadTimeout
public void setReadTimeout(long timeout, TimeUnit unit)
From source file:fr.eo.api.ApiErrorTest.java
License:Open Source License
@Ignore @Test(expected = RetrofitError.class) public void testTimeout() throws FileNotFoundException { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(1, TimeUnit.MILLISECONDS); client.setReadTimeout(1, TimeUnit.MILLISECONDS); AccountService accountService = new Manager().setClient(new OkClient(client)) .setErrorHandler(new NetworkErrorHandler() { @Override// w w w . jav a 2 s . co m public void onNoInternetError(RetrofitError cause) { System.err.println("No internet connection !"); } @Override public void onTimeOutError(RetrofitError cause) { assertTrue(true); } }).accountService(); TestCredential testCredential = getCredential(); accountService.apiKeyInfo(testCredential.keyID, testCredential.vCode); fail("No error occured !"); }
From source file:info.curtbinder.reefangel.service.ControllerTask.java
License:Creative Commons License
public void run() { // Communicate with controller // clear out the error code on run rapp.clearErrorCode();/*from w w w. j a v a 2s . c o m*/ Response response = null; boolean fInterrupted = false; broadcastUpdateStatus(R.string.statusStart); try { URL url = new URL(host.toString()); OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(host.getConnectTimeout(), TimeUnit.MILLISECONDS); client.setReadTimeout(host.getReadTimeout(), TimeUnit.MILLISECONDS); Request.Builder builder = new Request.Builder(); builder.url(url); if (host.isDeviceAuthenticationEnabled()) { String creds = Credentials.basic(host.getWifiUsername(), host.getWifiPassword()); builder.header("Authorization", creds); } Request req = builder.build(); broadcastUpdateStatus(R.string.statusConnect); response = client.newCall(req).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); if (Thread.interrupted()) throw new InterruptedException(); } catch (MalformedURLException e) { rapp.error(1, e, "MalformedURLException"); } catch (SocketTimeoutException e) { rapp.error(5, e, "SocketTimeoutException"); } catch (ConnectException e) { rapp.error(3, e, "ConnectException"); } catch (UnknownHostException e) { String msg = "Unknown Host: " + host.toString(); UnknownHostException ue = new UnknownHostException(msg); rapp.error(4, ue, "UnknownHostException"); } catch (EOFException e) { EOFException eof = new EOFException(rapp.getString(R.string.errorAuthentication)); rapp.error(3, eof, "EOFException"); } catch (IOException e) { rapp.error(3, e, "IOException"); } catch (InterruptedException e) { fInterrupted = true; } processResponse(response, fInterrupted); }
From source file:io.apiman.gateway.platforms.servlet.connectors.HttpConnectorFactory.java
License:Apache License
/** * @return a new http client/* www . ja v a 2s .c o m*/ */ private OkHttpClient createHttpClient() { OkHttpClient client = new OkHttpClient(); client.setReadTimeout(connectorOptions.getReadTimeout(), TimeUnit.SECONDS); client.setWriteTimeout(connectorOptions.getWriteTimeout(), TimeUnit.SECONDS); client.setConnectTimeout(connectorOptions.getConnectTimeout(), TimeUnit.SECONDS); client.setFollowRedirects(connectorOptions.isFollowRedirects()); client.setFollowSslRedirects(connectorOptions.isFollowRedirects()); client.setProxySelector(ProxySelector.getDefault()); client.setCookieHandler(CookieHandler.getDefault()); client.setCertificatePinner(CertificatePinner.DEFAULT); client.setAuthenticator(AuthenticatorAdapter.INSTANCE); client.setConnectionPool(ConnectionPool.getDefault()); client.setProtocols(Util.immutableList(Protocol.HTTP_1_1)); client.setConnectionSpecs(DEFAULT_CONNECTION_SPECS); client.setSocketFactory(SocketFactory.getDefault()); Internal.instance.setNetwork(client, Network.DEFAULT); return client; }
From source file:io.apptik.comm.jus.okhttp.OkHttpStack.java
License:Apache License
@Override public NetworkResponse performRequest(Request<?> request, Headers additionalHeaders, ByteArrayPool byteArrayPool) throws IOException { //clone to be able to set timeouts per call OkHttpClient client = this.client.clone(); client.setConnectTimeout(request.getRetryPolicy().getCurrentConnectTimeout(), TimeUnit.MILLISECONDS); client.setReadTimeout(request.getRetryPolicy().getCurrentReadTimeout(), TimeUnit.MILLISECONDS); com.squareup.okhttp.Request okRequest = new com.squareup.okhttp.Request.Builder() .url(request.getUrlString()).headers(JusOk.okHeaders(request.getHeaders(), additionalHeaders)) .tag(request.getTag()).method(request.getMethod(), JusOk.okBody(request.getNetworkRequest())) .build();/*from w w w . j av a 2s .c o m*/ long requestStart = System.nanoTime(); Response response = client.newCall(okRequest).execute(); byte[] data = null; if (NetworkDispatcher.hasResponseBody(request.getMethod(), response.code())) { data = getContentBytes(response.body().source(), byteArrayPool, (int) response.body().contentLength()); } else { // Add 0 byte response as a way of honestly representing a // no-content request. data = new byte[0]; } return new NetworkResponse.Builder().setHeaders(JusOk.jusHeaders(response.headers())) .setStatusCode(response.code()).setBody(data).setNetworkTimeNs(System.nanoTime() - requestStart) .build(); }
From source file:io.fabric8.docker.client.impl.AttachContainer.java
License:Apache License
private InputOutputErrorHandle doAttach(Boolean logs, Boolean stream) { try {/*from w w w. j av a 2s.c o m*/ StringBuilder sb = new StringBuilder(); sb.append(URLUtils.join(getOperationUrl().toString(), "ws")); sb.append("?").append(STREAM).append("=").append(true); sb.append("?").append(LOGS).append("=").append(true); sb.append("&").append(STDIN).append("=").append(in != null || inPipe != null); sb.append("&").append(STDOUT).append("=").append(out != null || outPipe != null); sb.append("&").append(STDERR).append("=").append(err != null || errPipe != null); Request.Builder r = new Request.Builder().url(sb.toString()).get(); OkHttpClient clone = client.clone(); clone.setReadTimeout(0, TimeUnit.MILLISECONDS); WebSocketCall webSocketCall = WebSocketCall.create(clone, r.build()); final ContainerInputOutputErrorHandle handle = new ContainerInputOutputErrorHandle(in, out, err, inPipe, outPipe, errPipe); webSocketCall.enqueue(handle); handle.waitUntilReady(); return handle; } catch (Throwable t) { throw DockerClientException.launderThrowable(t); } }
From source file:io.fabric8.docker.client.impl.BuildImage.java
License:Apache License
@Override public OutputHandle fromTar(String path) { try {// ww w. j av a 2s. c o m StringBuilder sb = new StringBuilder(); sb.append(getOperationUrl()); sb.append(Q).append(DOCKER_FILE).append(EQUALS).append(dockerFile); if (alwaysRemoveIntermediate) { sb.append(A).append(ALWAYS_REMOVE_INTERMEDIATE).append(EQUALS).append(alwaysRemoveIntermediate); } else { sb.append(A).append(REMOVE_INTERMEDIATE_ON_SUCCESS).append(EQUALS) .append(removeIntermediateOnSuccess); } sb.append(A).append(PULL).append(EQUALS).append(pulling); sb.append(A).append(SUPRESS_VERBOSE_OUT).append(EQUALS).append(supressingVerboseOutput); sb.append(A).append(NOCACHE).append(EQUALS).append(noCache); if (cpuPeriodMicros >= 0) { sb.append(A).append(CPU_PERIOD).append(EQUALS).append(cpuPeriodMicros); } if (cpuQuotaMicros >= 0) { sb.append(A).append(CPU_QUOTA).append(EQUALS).append(cpuQuotaMicros); } if (cpuShares >= 0) { sb.append(A).append(CPU_SHARES).append(EQUALS).append(cpuShares); } if (cpus > 0) { sb.append(A).append(CPUS).append(EQUALS).append(cpus); } if (Utils.isNotNullOrEmpty(memorySize)) { sb.append(A).append(MEMORY).append(EQUALS).append(memorySize); } if (Utils.isNotNullOrEmpty(swapSize)) { sb.append(A).append(MEMSWAP).append(EQUALS).append(swapSize); } if (Utils.isNotNullOrEmpty(buildArgs)) { sb.append(A).append(BUILD_ARGS).append(EQUALS).append(buildArgs); } if (Utils.isNotNullOrEmpty(repositoryName)) { sb.append(A).append(REPOSITORY_NAME).append(EQUALS).append(repositoryName); } RequestBody body = RequestBody.create(MEDIA_TYPE_TAR, new File(path)); Request request = new Request.Builder() .header("X-Registry-Config", new String(Base64.encodeBase64( JSON_MAPPER.writeValueAsString(config.getAuthConfigs()).getBytes("UTF-8")), "UTF-8")) .post(body).url(sb.toString()).build(); OkHttpClient clone = client.clone(); clone.setReadTimeout(config.getImageBuildTimeout(), TimeUnit.MILLISECONDS); BuildImageHandle handle = new BuildImageHandle(out, config.getImageBuildTimeout(), TimeUnit.MILLISECONDS, listener); clone.newCall(request).enqueue(handle); return handle; } catch (Exception e) { throw DockerClientException.launderThrowable(e); } }
From source file:io.fabric8.docker.client.impl.EventOperationImpl.java
License:Apache License
@Override public OutputHandle list() { try {/*from www.j av a 2s.c om*/ StringBuilder sb = new StringBuilder(); sb.append(getOperationUrl()).append(Q).append(FILTERS).append(EQUALS) .append(JSON_MAPPER.writeValueAsString(filters)); if (Utils.isNotNullOrEmpty(since)) { sb.append(A).append(SINCE).append(EQUALS).append(since); } if (Utils.isNotNullOrEmpty(until)) { sb.append(A).append(UNTIL).append(EQUALS).append(until); } Request request = new Request.Builder().get().url(sb.toString()).build(); OkHttpClient clone = client.clone(); clone.setReadTimeout(0, TimeUnit.NANOSECONDS); EventHandle handle = new EventHandle(new PipedOutputStream(), config.getRequestTimeout(), TimeUnit.MILLISECONDS); clone.newCall(request).enqueue(handle); return handle; } catch (Exception e) { throw DockerClientException.launderThrowable(e); } }
From source file:io.fabric8.docker.client.impl.GetLogsOfContainer.java
License:Apache License
private OutputHandle doGetLogHandle(Boolean follow) { try {//from w w w. j ava 2s . c o m StringBuilder sb = new StringBuilder(); sb.append(URLUtils.join(getOperationUrl().toString())); sb.append("?").append(FOLLOW).append("=").append(follow ? TRUE : FLASE); sb.append("&").append(STDOUT).append("=").append(out != null || outPipe != null ? TRUE : FLASE); sb.append("&").append(STDERR).append("=").append(err != null || errPipe != null ? TRUE : FLASE); if (isNotNullOrEmpty(since)) { sb.append("&").append(SINCE).append("=").append(since); } if (lines > 0) { sb.append("&").append(TAIL).append("=").append(lines); } else { sb.append("&").append(TAIL).append("=").append(ALL); } if (timestampsEnabled) { sb.append("&").append(TIMESTAMPS).append("=").append(TRUE); } Request request = new Request.Builder().url(sb.toString()).get().build(); OkHttpClient clone = client.clone(); clone.setReadTimeout(0, TimeUnit.MILLISECONDS); final ContainerLogHandle handle = new ContainerLogHandle(out, err, outPipe, errPipe); clone.newCall(request).enqueue(handle); handle.waitUntilReady(); return handle; } catch (Throwable t) { throw DockerClientException.launderThrowable(t); } }
From source file:io.fabric8.docker.client.impl.ImageOperationImpl.java
License:Apache License
@Override public List<SearchResult> search(String term) { try {/*from w w w .j a v a 2s. c o m*/ StringBuilder sb = new StringBuilder().append(getOperationUrl(SEARCH_OPERATION)).append(Q).append(TERM) .append(EQUALS).append(term); Request request = new Request.Builder().get().url(new URL(sb.toString())).get().build(); Response response = null; try { OkHttpClient clone = client.clone(); clone.setReadTimeout(config.getImageSearchTimeout(), TimeUnit.MILLISECONDS); response = clone.newCall(request).execute(); assertResponseCodes(request, response, 200); } catch (Exception e) { throw requestException(request, e); } return JSON_MAPPER.readValue(response.body().byteStream(), IMAGE_SEARCH_RESULT_LIST); } catch (Exception e) { throw DockerClientException.launderThrowable(e); } }
From source file:io.fabric8.docker.client.impl.ImportImage.java
License:Apache License
@Override public OutputHandle asRepo(String src) { try {/*from ww w. java 2 s. c o m*/ StringBuilder sb = new StringBuilder().append(getOperationUrl(CREATE_OPERATION)); if (Utils.isNotNullOrEmpty(tag)) { sb.append(Q).append(TAG).append(EQUALS).append(tag); } AuthConfig authConfig = RegistryUtils.getConfigForImage(name, config); Request request = new Request.Builder() .header("X-Registry-Auth", new String(Base64.encodeBase64(JSON_MAPPER .writeValueAsString(authConfig != null ? authConfig : new AuthConfig()) .getBytes("UTF-8")), "UTF-8")) .post(RequestBody.create(MEDIA_TYPE_TEXT, EMPTY)).url(sb.toString()).build(); OkHttpClient clone = client.clone(); clone.setReadTimeout(0, TimeUnit.MILLISECONDS); ImportImageHandle handle = new ImportImageHandle(out, config.getImagePushTimeout(), TimeUnit.MILLISECONDS, listener); clone.newCall(request).enqueue(handle); return handle; } catch (Exception e) { throw DockerClientException.launderThrowable(e); } }