Example usage for com.squareup.okhttp OkHttpClient setProxy

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

Introduction

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

Prototype

public OkHttpClient setProxy(Proxy proxy) 

Source Link

Document

Sets the HTTP proxy that will be used by connections created by this client.

Usage

From source file:com.android.mms.service_alt.MmsHttpClient.java

License:Apache License

/**
 * Open an HTTP connection/*w w w . j a v a2  s  .  c  o  m*/
 *
 * TODO: The following code is borrowed from android.net.Network.openConnection
 * Once that method supports proxy, we should use that instead
 * Also we should remove the associated HostResolver and ConnectionPool from
 * MmsNetworkManager
 *
 * @param url The URL to connect to
 * @param proxy The proxy to use
 * @return The opened HttpURLConnection
 * @throws MalformedURLException If URL is malformed
 */
private HttpURLConnection openConnection(URL url, final Proxy proxy) throws MalformedURLException {
    final String protocol = url.getProtocol();
    OkHttpClient okHttpClient;
    if (protocol.equals("http")) {
        okHttpClient = new OkHttpClient();
        okHttpClient.setFollowRedirects(false);
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        okHttpClient.setProxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                if (proxy != null) {
                    return Arrays.asList(proxy);
                } else {
                    return new ArrayList<Proxy>();
                }
            }

            @Override
            public void connectFailed(URI uri, SocketAddress address, IOException failure) {

            }
        });
        okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
        okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
        okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
        okHttpClient.setSocketFactory(SocketFactory.getDefault());
        Internal.instance.setNetwork(okHttpClient, mHostResolver);

        if (proxy != null) {
            okHttpClient.setProxy(proxy);
        }

        return new HttpURLConnectionImpl(url, okHttpClient);
    } else if (protocol.equals("https")) {
        okHttpClient = new OkHttpClient();
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
        okHttpClient.setHostnameVerifier(verifier);
        okHttpClient.setSslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory());
        okHttpClient.setProxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                return Arrays.asList(proxy);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress address, IOException failure) {

            }
        });
        okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
        okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
        okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
        Internal.instance.setNetwork(okHttpClient, mHostResolver);

        return new HttpsURLConnectionImpl(url, okHttpClient);
    } else {
        throw new MalformedURLException("Invalid URL or unrecognized protocol " + protocol);
    }
}

From source file:com.cdancy.artifactory.rest.config.ArtifactoryOkHttpCommandExecutorService.java

License:Apache License

@Override
protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException {

    OkHttpClient requestScopedClient = clientSupplier.get();
    requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri()));
    Response response = requestScopedClient.newCall(nativeRequest).execute();

    HttpResponse.Builder<?> builder = HttpResponse.builder();
    builder.statusCode(response.code());
    builder.message(response.message());

    Builder<String, String> headerBuilder = ImmutableMultimap.builder();
    Headers responseHeaders = response.headers();

    // Check for Artifactory header and init potential file for downstream use
    File destinationFile = null;/*from  w  ww . j a  v a  2 s  . co  m*/
    String artFileName = responseHeaders.get("X-Artifactory-Filename");
    if (artFileName != null) {

        GAVCoordinates gavCoordinates = ArtifactoryUtils.gavFromURL(nativeRequest.url(),
                endpoint.get().toURL());
        destinationFile = ArtifactoryUtils.getGradleFile(gavCoordinates, artFileName,
                responseHeaders.get("ETag"));
        headerBuilder.put(ArtifactoryUtils.LOCATION_HEADER, destinationFile.getAbsolutePath());
    }

    for (String header : responseHeaders.names()) {
        headerBuilder.putAll(header, responseHeaders.values(header));
    }

    ImmutableMultimap<String, String> headers = headerBuilder.build();

    if (response.code() == 204 && response.body() != null) {
        response.body().close();
    } else {
        if (destinationFile != null) {
            if (!destinationFile.exists() || (destinationFile.length() != response.body().contentLength())) {
                InputStream inputStream = null;
                try {
                    inputStream = response.body().byteStream();
                    ArtifactoryUtils.resolveInputStream(inputStream, destinationFile);
                } catch (Exception e) {
                    Throwables.propagate(e);
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            }
            IOUtils.closeQuietly(response.body().byteStream());
        } else {
            Payload payload = newInputStreamPayload(response.body().byteStream());
            contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);
            builder.payload(payload);
        }
    }

    builder.headers(filterOutContentHeaders(headers));
    return builder.build();
}

From source file:com.peach.masktime.module.net.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();
    LogUtils.i(TAG, "timeoutMs = " + timeoutMs);
    client.setProxy(Proxy.NO_PROXY);
    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));
    }//  w w w .  j ava 2s  .  c o  m
    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:fr.eo.api.ApiErrorTest.java

License:Open Source License

@Ignore
@Test(expected = RetrofitError.class)
public void testNoInternet() throws FileNotFoundException {

    OkHttpClient client = new OkHttpClient();
    client.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("toto", 1234)));

    AccountService accountService = new Manager().setClient(new OkClient(client))
            .setErrorHandler(new NetworkErrorHandler() {
                @Override/*w  w w  .j av  a  2s .  c o m*/
                public void onNoInternetError(RetrofitError cause) {
                    assertTrue(true);
                }

                @Override
                public void onTimeOutError(RetrofitError cause) {
                    fail("No Time out here !");
                }
            }).accountService();

    TestCredential testCredential = getCredential();

    accountService.apiKeyInfo(testCredential.keyID, testCredential.vCode);

    fail("No error occured !");
}

From source file:io.fabric8.docker.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {//from www .ja  v  a 2s.c  o m
        OkHttpClient httpClient = new OkHttpClient();

        httpClient.setConnectionPool(ConnectionPool.getDefault());
        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        if (usesUnixSocket(config)) {
            URL masterURL = new URL(config.getDockerUrl().replaceFirst(UNIX_SCHEME, FILE_SCHEME));
            httpClient.setSocketFactory(new UnixSocketFactory(masterURL.getFile()));
            config.setDockerUrl(UNIX_FAKE_URL);
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    for (int i = 0, size = challenges.size(); i < size; i++) {
                        Challenge challenge = challenges.get(i);
                        if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                            continue;

                        String credential = Credentials.basic(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getDockerUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getDockerUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new DockerClientException("Invalid proxy server configuration", e);
            }
        }

        return httpClient;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.kubernetes.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {/*  ww w .ja  v  a2 s.co  m*/
        OkHttpClient httpClient = new OkHttpClient();

        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    for (int i = 0, size = challenges.size(); i < size; i++) {
                        Challenge challenge = challenges.get(i);
                        if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                            continue;

                        String credential = Credentials.basic(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getMasterUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getMasterUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new KubernetesClientException("Invalid proxy server configuration", e);
            }
        }

        if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) {
            httpClient.networkInterceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent())
                            .build();
                    return chain.proceed(agent);
                }
            });
        }

        return httpClient;
    } catch (Exception e) {
        throw KubernetesClientException.launderThrowable(e);
    }
}

From source file:io.scal.secureshare.controller.ArchiveSiteController.java

@Override
public void upload(Account account, HashMap<String, String> valueMap) {
    Timber.d("Upload file: Entering upload");

    String mediaPath = valueMap.get(VALUE_KEY_MEDIA_PATH);
    boolean useTor = (valueMap.get(VALUE_KEY_USE_TOR).equals("true")) ? true : false;
    String fileName = mediaPath.substring(mediaPath.lastIndexOf("/") + 1, mediaPath.length());
    String licenseUrl = valueMap.get(VALUE_KEY_LICENSE_URL);

    // TODO this should make sure we arn't accidentally using one of archive.org's metadata fields by accident
    String title = valueMap.get(VALUE_KEY_TITLE);
    boolean shareTitle = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_TITLE).equals("true")) ? true
            : false;/*from  w  w w .ja va 2s.  co  m*/
    String slug = valueMap.get(VALUE_KEY_SLUG);
    String tags = valueMap.get(VALUE_KEY_TAGS);
    //always want to include these two tags
    tags += "presssecure,storymaker";
    boolean shareTags = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_TAGS).equals("true")) ? true
            : false;
    String author = valueMap.get(VALUE_KEY_AUTHOR);
    boolean shareAuthor = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_AUTHOR).equals("true"))
            ? true
            : false;
    String profileUrl = valueMap.get(VALUE_KEY_PROFILE_URL);
    String locationName = valueMap.get(VALUE_KEY_LOCATION_NAME);
    boolean shareLocation = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_LOCATION).equals("true"))
            ? true
            : false;
    String body = valueMap.get(VALUE_KEY_BODY);
    boolean shareDescription = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_DESCRIPTION)
            .equals("true")) ? true : false;

    File file = new File(mediaPath);
    if (!file.exists()) {
        jobFailed(null, 4000473, "Internet Archive upload failed: invalid file");
        return;
    }

    String mediaType = Util.getMediaType(mediaPath);

    OkHttpClient client = new OkHttpClient();

    if (super.torCheck(useTor, super.mContext)) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ORBOT_HOST, ORBOT_HTTP_PORT));
        client.setProxy(proxy);
    }

    // FIXME we are putting a random 4 char string in the bucket name for collision avoidance, we might want to do this differently?
    String urlPath = null;
    String url = null;
    if (shareTitle) {
        String randomString = new Util.RandomString(4).nextString();
        urlPath = slug + "-" + randomString;
        url = ARCHIVE_API_ENDPOINT + "/" + urlPath + "/" + fileName;
    } else {
        urlPath = new Util.RandomString(16).nextString(); // FIXME need to use real GUIDs
        url = ARCHIVE_API_ENDPOINT + "/" + urlPath + "/" + fileName;
    }
    Timber.d("uploading to url: " + url);

    Request.Builder builder = new Request.Builder().url(url).put(RequestBody.create(MEDIA_TYPE, file))
            .addHeader("Accept", "*/*").addHeader("x-amz-auto-make-bucket", "1")
            //                .addHeader("x-archive-meta-collection", "storymaker")
            //            .addHeader("x-archive-meta-sponsor", "Sponsor 998")
            .addHeader("x-archive-meta-language", "eng") // FIXME pull meta language from story
            .addHeader("authorization", "LOW " + account.getUserName() + ":" + account.getCredentials());

    if (shareAuthor && author != null) {
        builder.addHeader("x-archive-meta-author", author);
        if (profileUrl != null) {
            builder.addHeader("x-archive-meta-authorurl", profileUrl);
        }
    }

    if (mediaType != null) {
        builder.addHeader("x-archive-meta-mediatype", mediaType);
        if (mediaType.contains("audio")) {
            builder.addHeader("x-archive-meta-collection", "opensource_audio");
        } else {
            builder.addHeader("x-archive-meta-collection", "opensource_movies");
        }
    } else {
        builder.addHeader("x-archive-meta-collection", "opensource_movies");
    }

    if (shareLocation && locationName != null) {
        builder.addHeader("x-archive-meta-location", locationName);
    }

    if (shareTags && tags != null) {
        String keywords = tags.replace(',', ';').replaceAll(" ", "");
        builder.addHeader("x-archive-meta-subject", keywords);
    }

    if (shareDescription && body != null) {
        builder.addHeader("x-archive-meta-description", body);
    }

    if (shareTitle && title != null) {
        builder.addHeader("x-archive-meta-title", title);
    }

    if (licenseUrl != null) {
        builder.addHeader("x-archive-meta-licenseurl", licenseUrl);
    }

    Request request = builder.build();

    UploadFileTask uploadFileTask = new UploadFileTask(client, request);
    uploadFileTask.execute();
}

From source file:io.scal.secureshareui.controller.ArchiveSiteController.java

@Override
public void upload(Account account, HashMap<String, String> valueMap) {
    Log.d(TAG, "Upload file: Entering upload");

    String mediaPath = valueMap.get(VALUE_KEY_MEDIA_PATH);
    boolean useTor = (valueMap.get(VALUE_KEY_USE_TOR).equals("true")) ? true : false;
    String fileName = mediaPath.substring(mediaPath.lastIndexOf("/") + 1, mediaPath.length());
    String licenseUrl = valueMap.get(VALUE_KEY_LICENSE_URL);

    // TODO this should make sure we arn't accidentally using one of archive.org's metadata fields by accident
    String title = valueMap.get(VALUE_KEY_TITLE);
    boolean shareTitle = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_TITLE).equals("true")) ? true
            : false;/*from ww  w  .j  a  v a  2  s . c o m*/
    String slug = valueMap.get(VALUE_KEY_SLUG);
    String tags = valueMap.get(VALUE_KEY_TAGS);
    //always want to include these two tags
    tags += "presssecure,storymaker";
    boolean shareTags = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_TAGS).equals("true")) ? true
            : false;
    String author = valueMap.get(VALUE_KEY_AUTHOR);
    boolean shareAuthor = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_AUTHOR).equals("true"))
            ? true
            : false;
    String profileUrl = valueMap.get(VALUE_KEY_PROFILE_URL);
    String locationName = valueMap.get(VALUE_KEY_LOCATION_NAME);
    boolean shareLocation = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_LOCATION).equals("true"))
            ? true
            : false;
    String body = valueMap.get(VALUE_KEY_BODY);
    boolean shareDescription = (valueMap.get(ArchiveMetadataActivity.INTENT_EXTRA_SHARE_DESCRIPTION)
            .equals("true")) ? true : false;

    File file = new File(mediaPath);
    if (!file.exists()) {
        jobFailed(null, 4000473, "Internet Archive upload failed: invalid file");
        return;
    }

    String mediaType = Util.getMediaType(mediaPath);

    OkHttpClient client = new OkHttpClient();

    if (super.torCheck(useTor, super.mContext)) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ORBOT_HOST, ORBOT_HTTP_PORT));
        client.setProxy(proxy);
    }

    // FIXME we are putting a random 4 char string in the bucket name for collision avoidance, we might want to do this differently?
    String urlPath = null;
    String url = null;
    if (shareTitle) {
        String randomString = new Util.RandomString(4).nextString();
        urlPath = slug + "-" + randomString;
        url = ARCHIVE_API_ENDPOINT + "/" + urlPath + "/" + fileName;
    } else {
        urlPath = new Util.RandomString(16).nextString(); // FIXME need to use real GUIDs
        url = ARCHIVE_API_ENDPOINT + "/" + urlPath + "/" + fileName;
    }
    Log.d(TAG, "uploading to url: " + url);

    Request.Builder builder = new Request.Builder().url(url).put(RequestBody.create(MEDIA_TYPE, file))
            .addHeader("Accept", "*/*").addHeader("x-amz-auto-make-bucket", "1")
            //                .addHeader("x-archive-meta-collection", "storymaker")
            //            .addHeader("x-archive-meta-sponsor", "Sponsor 998")
            .addHeader("x-archive-meta-language", "eng") // FIXME pull meta language from story
            .addHeader("authorization", "LOW " + account.getUserName() + ":" + account.getCredentials());

    if (shareAuthor && author != null) {
        builder.addHeader("x-archive-meta-author", author);
        if (profileUrl != null) {
            builder.addHeader("x-archive-meta-authorurl", profileUrl);
        }
    }

    if (mediaType != null) {
        builder.addHeader("x-archive-meta-mediatype", mediaType);
        if (mediaType.contains("audio")) {
            builder.addHeader("x-archive-meta-collection", "opensource_audio");
        } else {
            builder.addHeader("x-archive-meta-collection", "opensource_movies");
        }
    } else {
        builder.addHeader("x-archive-meta-collection", "opensource_movies");
    }

    if (shareLocation && locationName != null) {
        builder.addHeader("x-archive-meta-location", locationName);
    }

    if (shareTags && tags != null) {
        String keywords = tags.replace(',', ';').replaceAll(" ", "");
        builder.addHeader("x-archive-meta-subject", keywords);
    }

    if (shareDescription && body != null) {
        builder.addHeader("x-archive-meta-description", body);
    }

    if (shareTitle && title != null) {
        builder.addHeader("x-archive-meta-title", title);
    }

    if (licenseUrl != null) {
        builder.addHeader("x-archive-meta-licenseurl", licenseUrl);
    }

    Request request = builder.build();

    UploadFileTask uploadFileTask = new UploadFileTask(client, request);
    uploadFileTask.execute();
}

From source file:io.takari.aether.okhttp.OkHttpAetherClient.java

License:Open Source License

public OkHttpAetherClient(AetherClientConfig config) {
    this.config = config;

    // headers are modified during http auth handshake
    // make a copy to avoid cross-talk among client instances
    headers = new HashMap<String, String>();
    if (config.getHeaders() != null) {
        headers.putAll(config.getHeaders());
    }//www .j  ava2  s.  co  m

    //
    // If the User-Agent has been overriden in the headers then we will use that
    //
    if (!headers.containsKey("User-Agent")) {
        headers.put("User-Agent", config.getUserAgent());
    }

    OkHttpClient httpClient = new OkHttpClient();
    httpClient.setProxy(getProxy(config.getProxy()));
    httpClient.setHostnameVerifier(OkHostnameVerifier.INSTANCE);
    httpClient.setAuthenticator(NOAUTH); // see #authenticate below
    httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
    httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
    httpClient.setSslSocketFactory(config.getSslSocketFactory());
    this.httpClient = httpClient;
}

From source file:org.apache.nifi.processors.standard.InvokeHTTP.java

License:Apache License

@OnScheduled
public void setUpClient(final ProcessContext context) throws IOException {
    okHttpClientAtomicReference.set(null);

    OkHttpClient okHttpClient = new OkHttpClient();

    // Add a proxy if set
    final String proxyHost = context.getProperty(PROP_PROXY_HOST).getValue();
    final Integer proxyPort = context.getProperty(PROP_PROXY_PORT).asInteger();
    if (proxyHost != null && proxyPort != null) {
        final Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        okHttpClient.setProxy(proxy);
    }/*from www .j  a v a  2  s  .c  o m*/

    // Set timeouts
    okHttpClient.setConnectTimeout(
            (context.getProperty(PROP_CONNECT_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()),
            TimeUnit.MILLISECONDS);
    okHttpClient.setReadTimeout(
            context.getProperty(PROP_READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue(),
            TimeUnit.MILLISECONDS);

    // Set whether to follow redirects
    okHttpClient.setFollowRedirects(context.getProperty(PROP_FOLLOW_REDIRECTS).asBoolean());

    final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslService == null ? null : sslService.createSSLContext(ClientAuth.NONE);

    // check if the ssl context is set and add the factory if so
    if (sslContext != null) {
        okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
    }

    // check the trusted hostname property and override the HostnameVerifier
    String trustedHostname = trimToEmpty(context.getProperty(PROP_TRUSTED_HOSTNAME).getValue());
    if (!trustedHostname.isEmpty()) {
        okHttpClient.setHostnameVerifier(
                new OverrideHostnameVerifier(trustedHostname, okHttpClient.getHostnameVerifier()));
    }

    setAuthenticator(okHttpClient, context);

    useChunked = context.getProperty(PROP_USE_CHUNKED_ENCODING).asBoolean();

    okHttpClientAtomicReference.set(okHttpClient);
}