Example usage for com.squareup.okhttp OkHttpClient setWriteTimeout

List of usage examples for com.squareup.okhttp OkHttpClient setWriteTimeout

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient setWriteTimeout.

Prototype

public void setWriteTimeout(long timeout, TimeUnit unit) 

Source Link

Document

Sets the default write timeout for new connections.

Usage

From source file:apijson.demo.client.manager.HttpManager.java

License:Apache License

/**
 * @param url//from   w w  w. j  ava  2 s.co m
 * @return
 */
private OkHttpClient getHttpClient(String url) {
    Log.i(TAG, "getHttpClient  url = " + url);
    if (StringUtil.isNotEmpty(url, true) == false) {
        Log.e(TAG, "getHttpClient  StringUtil.isNotEmpty(url, true) == false >> return null;");
        return null;
    }

    OkHttpClient client = new OkHttpClient();
    client.setCookieHandler(new HttpHead());
    client.setConnectTimeout(15, TimeUnit.SECONDS);
    client.setWriteTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(10, TimeUnit.SECONDS);

    return client;
}

From source file:augsburg.se.alltagsguide.ServicesModule.java

License:Open Source License

@Singleton
@Provides/*from   w ww .  j ava2 s.com*/
OkHttpClient okHttpClient(Context context, @Named("cacheDir") File cachedir) {
    Ln.d("okHttpClient is intialized.");
    int cacheSize = 50 * 1024 * 1024; // 50 MiB
    Cache cache = new Cache(cachedir, cacheSize);
    OkHttpClient client = new OkHttpClient();
    client.setCache(cache);
    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setWriteTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
    return client;
}

From source file:cn.finalteam.okhttpfinal.OkHttpFactory.java

License:Apache License

public static OkHttpClient getOkHttpClientFactory(long timeout) {
    OkHttpClient client = new OkHttpClient();
    ////from   w ww.  j ava2  s . c o m
    client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
    //???
    client.setRetryOnConnectionFailure(false);
    //???
    client.setFollowRedirects(true);
    //?cookie
    client.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));

    return client;
}

From source file:com.aix.city.comm.OkHttpStack.java

License:Open Source License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/*from www  .j  av a  2s  .  c  om*/
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:com.burhan.udacity.popularmovies.data.DataModule.java

License:Apache License

static OkHttpClient createOkHttpClient(Application app) {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, SECONDS);
    client.setReadTimeout(10, SECONDS);/*www .  j a  v a  2  s. co  m*/
    client.setWriteTimeout(10, SECONDS);

    // Install an HTTP cache in the application cache directory.
    File cacheDir = new File(app.getCacheDir(), "http");
    Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
    client.setCache(cache);

    return client;
}

From source file:com.datastore_android_sdk.okhttp.OkHttpStack.java

License:Open Source License

@Override
public URLHttpResponse performRequest(Request<?> request, ArrayList<HttpParamsEntry> additionalHeaders)
        throws IOException {
    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    for (final HttpParamsEntry entry : request.getHeaders()) {
        okHttpRequestBuilder.addHeader(entry.k, entry.v);
    }//ww  w .  ja  v a  2s.c om
    for (final HttpParamsEntry entry : additionalHeaders) {
        okHttpRequestBuilder.addHeader(entry.k, entry.v);
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);
    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    return responseFromConnection(okHttpResponse);
}

From source file:com.dzhyun.sdk.DzhChannel.java

License:Open Source License

@ReactMethod
public void connect(final String url, final int id) {
    OkHttpClient client = new OkHttpClient();

    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setWriteTimeout(10, TimeUnit.SECONDS);
    // Disable timeouts for read
    client.setReadTimeout(0, TimeUnit.MINUTES);

    Request request = new Request.Builder().tag(id).url(url).build();

    WebSocketCall.create(client, request).enqueue(new WebSocketListener() {

        @Override//from  ww w .  j a va  2 s. c  om
        public void onOpen(WebSocket webSocket, Response response) {
            mWebSocketConnections.put(id, webSocket);
            WritableMap params = Arguments.createMap();
            params.putInt("id", id);
            sendEvent("dzhChannelOpen", params);
        }

        @Override
        public void onClose(int code, String reason) {
            WritableMap params = Arguments.createMap();
            params.putInt("id", id);
            params.putInt("code", code);
            params.putString("reason", reason);
            sendEvent("dzhChannelClosed", params);
        }

        @Override
        public void onFailure(IOException e, Response response) {
            notifyWebSocketFailed(id, e.getMessage());
        }

        @Override
        public void onPong(Buffer buffer) {
        }

        @Override
        public void onMessage(BufferedSource bufferedSource, WebSocket.PayloadType payloadType) {
            String message;
            if (payloadType == WebSocket.PayloadType.BINARY) {

                try {
                    message = Pb2Json.toJson(bufferedSource.readByteArray());
                    bufferedSource.close();
                } catch (IOException e) {
                    FLog.e(ReactConstants.TAG, "decode pb failed " + id, e);
                    return;
                }

            } else {
                try {
                    message = bufferedSource.readUtf8();
                } catch (IOException e) {
                    notifyWebSocketFailed(id, e.getMessage());
                    return;
                }
                try {
                    bufferedSource.close();
                } catch (IOException e) {
                    FLog.e(ReactConstants.TAG, "Could not close BufferedSource for WebSocket id " + id, e);
                }

            }

            WritableMap params = Arguments.createMap();
            params.putInt("id", id);
            params.putString("data", message);
            sendEvent("dzhChannelMessage", params);
        }
    });

    // Trigger shutdown of the dispatcher's executor so this process can exit cleanly
    client.getDispatcher().getExecutorService().shutdown();
}

From source file:com.facebook.buck.cli.BuildCommand.java

License:Apache License

private int executeDistributedBuild(CommandRunnerParams params) throws IOException {
    ProjectFilesystem filesystem = params.getCell().getFilesystem();

    if (distributedBuildStateFile != null) {
        Path stateDumpPath = Paths.get(distributedBuildStateFile);
        TTransport transport;/*from   w ww  .j a  v  a  2s. c o  m*/
        boolean loading = Files.exists(stateDumpPath);
        if (loading) {
            transport = new TIOStreamTransport(filesystem.newFileInputStream(stateDumpPath));
        } else {
            transport = new TIOStreamTransport(filesystem.newFileOutputStream(stateDumpPath));
        }
        transport = new TZlibTransport(transport);
        TProtocol protocol = new TTupleProtocol(transport);

        try {
            if (loading) {
                DistributedBuildState state = DistributedBuildState.load(protocol);
                BuckConfig buckConfig = state.createBuckConfig(filesystem);
                params.getBuckEventBus()
                        .post(ConsoleEvent.info("Done loading state. Aliases: %s", buckConfig.getAliases()));
            } else {
                BuckConfig buckConfig = params.getBuckConfig();
                BuildJobState jobState = DistributedBuildState.dump(buckConfig);
                jobState.write(protocol);
                transport.flush();
            }
        } catch (TException e) {
            throw new RuntimeException(e);
        } finally {
            transport.close();
        }
    }

    DistBuildConfig config = new DistBuildConfig(params.getBuckConfig());
    ClientSideSlb slb = config.getFrontendConfig().createHttpClientSideSlb(params.getClock(),
            params.getBuckEventBus());
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(config.getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS);
    client.setReadTimeout(config.getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS);
    client.setWriteTimeout(config.getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS);

    try (HttpService httpService = new LoadBalancedService(slb, client, params.getBuckEventBus());
            ThriftService<FrontendRequest, FrontendResponse> service = new ThriftOverHttpService<>(
                    ThriftOverHttpServiceConfig.of(httpService))) {
        DistributedBuild build = new DistributedBuild(new DistBuildService(service, params.getBuckEventBus()));
        return build.executeAndPrintFailuresToEventBus();
    }
}

From source file:com.frostwire.http.HttpClient.java

License:Open Source License

private static OkHttpClient buildDefaultClient() {
    OkHttpClient c = new OkHttpClient();

    c.setFollowRedirects(true);/*  ww w .  j a  v a2s  .co  m*/
    c.setFollowSslRedirects(true);
    c.setConnectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    c.setReadTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    c.setWriteTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    c.setHostnameVerifier(buildHostnameVerifier());
    c.setSslSocketFactory(buildSSLSocketFactory());
    c.interceptors().add(new GzipInterceptor());

    return c;
}

From source file:com.gezhii.fitgroup.network.OkHttpStack.java

License:Open Source License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    //int timeoutMs = request.getTimeoutMs();
    int timeoutMs = 30000;
    Log.i("timeoutMs", timeoutMs);
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/*from  w  w w.  jav a 2  s  .c  om*/
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}