Example usage for com.squareup.okhttp OkHttpClient OkHttpClient

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

Introduction

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

Prototype

public OkHttpClient() 

Source Link

Usage

From source file:io.promagent.it.WildflyIT.java

License:Apache License

/**
 * Run some HTTP queries against a Docker container from image promagent/wildfly-kitchensink-promagent.
 * <p/>/* w  w  w .java 2s.co  m*/
 * The Docker container is started by the maven-docker-plugin when running <tt>mvn verify -Pwildfly</tt>.
 */
@Test
public void testWildfly() throws Exception {
    OkHttpClient client = new OkHttpClient();
    Request restRequest = new Request.Builder().url(System.getProperty("deployment.url") + "/rest/members")
            .build();

    // Execute REST call
    Response restResponse = client.newCall(restRequest).execute();
    Assertions.assertEquals(restResponse.code(), 200);
    Assertions.assertTrue(restResponse.body().string().contains("John Smith"));

    Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric
    assertMetrics(client, "1.0");

    // Execute REST call again
    restResponse = client.newCall(restRequest).execute();
    Assertions.assertEquals(restResponse.code(), 200);
    Assertions.assertTrue(restResponse.body().string().contains("John Smith"));

    Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric
    assertMetrics(client, "2.0");
}

From source file:io.reark.rxgithubapp.network.NetworkModule.java

License:Open Source License

@Provides
@Singleton//from w w  w.j av  a  2 s.  c o m
public OkHttpClient provideOkHttpClient(NetworkInstrumentation<OkHttpClient> networkInstrumentation) {
    return networkInstrumentation.decorateNetwork(new OkHttpClient());
}

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;/*  w w  w  . j  a  v a2s . 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;
    }
    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   www.  j  av  a2s.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());
    }/*from   ww  w.jav  a2s  . c om*/

    //
    // 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:it.analysis.ReportDumpTest.java

License:Open Source License

private void verifyUrl(String url) throws IOException {
    HttpUrl httpUrl = HttpUrl.parse(url);
    Request request = new Request.Builder().url(httpUrl).get().build();
    Response response = new OkHttpClient().newCall(request).execute();
    assertThat(response.isSuccessful()).as(httpUrl.toString()).isTrue();
    assertThat(response.body().string()).as(httpUrl.toString()).isNotEmpty();
}

From source file:it.http.HttpHeadersTest.java

License:Open Source License

private static Response call(String url) {
    Request request = new Request.Builder().get().url(url).build();
    try {//from ww  w.j  a v  a 2s . c o m
        return new OkHttpClient().newCall(request).execute();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:it.smartcommunitylab.ApiClient.java

License:Apache License

public ApiClient() {
    httpClient = new OkHttpClient();

    verifyingSsl = true;/*  ww w. ja va  2 s  . c  om*/

    json = new JSON();

    // Set default User-Agent.
    setUserAgent("Swagger-Codegen/1.0.0/java");

    // Setup authentications (key: authentication name, value: authentication).
    authentications = new HashMap<String, Authentication>();
    authentications.put("basic", new HttpBasicAuth());
    authentications.put("oauth2", new OAuth());
    // Prevent the authentications from being modified.
    authentications = Collections.unmodifiableMap(authentications);
}

From source file:it.smartcommunitylab.ApiClient.java

License:Apache License

public ApiClient(String hostUrl) {

    basePath = hostUrl;/*  w ww  . jav  a  2s.  c om*/

    httpClient = new OkHttpClient();

    verifyingSsl = true;

    json = new JSON();

    // Set default User-Agent.
    setUserAgent("Swagger-Codegen/1.0.0/java");

    // Setup authentications (key: authentication name, value: authentication).
    authentications = new HashMap<String, Authentication>();
    authentications.put("basic", new HttpBasicAuth());
    authentications.put("oauth2", new OAuth());
    // Prevent the authentications from being modified.
    authentications = Collections.unmodifiableMap(authentications);
}

From source file:it_minds.dk.eindberetningmobil_android.server.ServerHandler.java

License:Mozilla Public License

public ServerHandler(Context context) {
    queue = Volley.newRequestQueue(context, new OkHttpStack(new OkHttpClient()));
    defaultPolicy = new DefaultRetryPolicy(RETRY_MS, RETRY_COUNT, 1.5f); //6 secounds in the beginning.
}