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:com.yossisegev.apiwithrxjavademo.api.ApiObservable.java

License:Apache License

private ApiObservable(final ApiRequest apiRequest, Class<T> apiResponse) {

    if (mOkHttpClient == null) {
        mOkHttpClient = new OkHttpClient();
    }/*from  w  w w .  j  a  v  a  2s  .c om*/

    mApiRequest = apiRequest;
    mApiResponse = apiResponse;
    mObservable = buildObservable();
}

From source file:com.zachklipp.jfavicon.FaviconLoader.java

License:Apache License

public FaviconLoader() {
    client = new OkHttpHttpClient(new OkHttpClient());
    worker = SynchronousExecutor.getInstance();
    responder = SynchronousExecutor.getInstance();
}

From source file:com.zenstyle.muzei.wlppr.WlpprArtSource.java

License:Apache License

@Override
protected void onTryUpdate(int reason) throws RetryException {
    String currentToken = (getCurrentArtwork() != null) ? getCurrentArtwork().getToken() : null;

    LOGD(TAG, "Start trying to update Wlppr for Muzei");

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("http://wlppr.com")
            .setClient(new OkClient(new OkHttpClient())).setErrorHandler(new ErrorHandler() {
                @Override/*  www .  j  a  v a  2 s. c  om*/
                public Throwable handleError(RetrofitError retrofitError) {
                    int statusCode = retrofitError.getResponse() != null
                            ? retrofitError.getResponse().getStatus()
                            : 500;
                    if (retrofitError.isNetworkError() || (500 <= statusCode && statusCode < 600)) {
                        return new RetryException();
                    }
                    scheduleUpdate(System.currentTimeMillis() + ROTATE_TIME_MILLIS);
                    return retrofitError;
                }
            }).setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.BASIC).build();

    WlpprService service = restAdapter.create(WlpprService.class);
    WlpprService.WlpprResponse response = service.getWallPapers(300);

    if (response == null || response.wallpapers == null) {
        throw new RetryException();
    }

    if (response.wallpapers.size() == 0) {
        LOGW(TAG, "No wallpaper returned from API.");
        scheduleUpdate(System.currentTimeMillis() + ROTATE_TIME_MILLIS);
        return;
    }

    Random random = new Random();
    WlpprService.Wallpaper wallpaper;
    String token;
    int id;
    while (true) {
        wallpaper = response.wallpapers.get(random.nextInt(response.wallpapers.size()));
        id = wallpaper.id;
        token = Integer.toString(id);
        if (!token.equals(currentToken)) {
            break;
        }
    }

    String url = String.format(Locale.US, "http://wlppr.com/wallpapers/%1$d/%1$d.jpg", id);

    LOGD(TAG, "Wallpaper URL: " + url);

    publishArtwork(new Artwork.Builder().title(getString(R.string.wallpaper_name, id))
            .byline(getString(R.string.byline)).imageUri(Uri.parse(url)).token(token)
            .viewIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url))).build());

    scheduleUpdate(System.currentTimeMillis() + ROTATE_TIME_MILLIS);
}

From source file:de.dev.eth0.rssreader.app.http.HttpLoaderImpl.java

License:Apache License

private HttpLoaderImpl(Context context) {
    this.client = new OkHttpClient();
    this.context = context;
    Cache cache = getCache(context);// w  w w .j a  v  a  2s.c  o  m
    if (cache != null) {
        Timber.d("Setting cache");
        client.setCache(cache);
    }
}

From source file:de.ebf.GetTranslationsOneSkyAppMojo.java

License:Apache License

private void getTranslations() throws MojoExecutionException {
    try {//from w w w.ja v  a2s .  c o m
        for (String sourceFileName : sourceFileNames) {
            for (String locale : locales) {
                System.out
                        .println(String.format("Downloading %1s translations for %2s", locale, sourceFileName));

                OkHttpClient okHttpClient = new OkHttpClient();
                final String url = String.format(
                        API_ENDPOINT + "projects/%1$s/translations?locale=%2$s&source_file_name=%3$s&%4$s",
                        projectId, locale, sourceFileName, getAuthParams());
                final Request request = new Request.Builder().get().url(url).build();
                final Response response = okHttpClient.newCall(request).execute();

                if (response.code() == 200) {
                    if (!outputDir.exists()) {
                        outputDir.mkdirs();
                    }
                    //even though the OneSkyApp API documentation states that the file name should be sourceFileName_locale.sourceFileNameExtension, it is just locale.sourceFileNameExtension)
                    //https://github.com/onesky/api-documentation-platform/blob/master/resources/translation.md

                    String targetFileName = sourceFileName + "_" + locale;
                    int index = sourceFileName.lastIndexOf(".");
                    if (index > 0) {
                        targetFileName = sourceFileName.substring(0, index) + "_" + locale + "."
                                + sourceFileName.substring(index + 1);
                    }
                    File outputFile = new File(outputDir, targetFileName);
                    outputFile.createNewFile();
                    final InputStream inputStream = response.body().byteStream();
                    FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
                    IOUtils.copy(inputStream, fileOutputStream);
                    System.out.println(String.format("Successfully downloaded %1s translation for %2s to %3s",
                            locale, sourceFileName, outputFile.getName()));
                } else {
                    throw new MojoExecutionException(String.format("OneSkyApp API returned %1$s: %2s",
                            response.code(), response.message()));
                }
            }
        }
    } catch (IOException | MojoExecutionException ex) {
        if (failOnError == null || failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            System.out.println("Caught exception: " + ex.getMessage());
        }
    }
}

From source file:de.ebf.UploadFileOneSkyAppMojo.java

License:Apache License

private void uploadFiles() throws MojoExecutionException {
    try {/*from w w  w.j  av a 2  s  . c o  m*/
        for (File file : files) {
            System.out.println(String.format("Uploading %1$s", file.getName()));
            OkHttpClient okHttpClient = new OkHttpClient();
            final String url = String.format(
                    API_ENDPOINT + "projects/%1$s/files?file_format=%2$s&locale=%3$s&%4$s", projectId,
                    fileFormat, locale, getAuthParams());

            RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                    .addPart(
                            Headers.of("Content-Disposition",
                                    "form-data; name=\"file\"; filename=\"" + file.getName() + "\""),
                            RequestBody.create(MediaType.parse("text/plain"), file))
                    .build();

            final Request request = new Request.Builder().post(requestBody).url(url).build();
            final Response response = okHttpClient.newCall(request).execute();

            if (response.code() == 201) {
                System.out.println(String.format("Successfully uploaded %1$s", file.getName()));
            } else {
                throw new MojoExecutionException(String.format("OneSkyApp API returned %1$s: %2s, %3$s",
                        response.code(), response.message(), response.body().string()));
            }
        }
    } catch (IOException | MojoExecutionException ex) {
        if (failOnError == null || failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            System.out.println("Caught exception: " + ex.getMessage());
        }
    }
}

From source file:de.feike.tiingoclient.ApiClient.java

License:Apache License

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

    verifyingSsl = true;/*from w  w  w  . j a v  a2 s .  c  om*/

    json = new JSON(this);

    /*
     * Use RFC3339 format for date and datetime. See
     * http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
     */
    this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // Always use UTC as the default time zone when dealing with date
    // (without time).
    this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    initDatetimeFormat();

    // Be lenient on datetime formats when parsing datetime from string.
    // See <code>parseDatetime</code>.
    this.lenientDatetimeFormat = true;

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

}

From source file:de.l3s.boilerpipe.sax.HTMLFetcher.java

License:Apache License

public static HTMLDocument fetchOk(final String url) throws IOException {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();

    Response response = client.newCall(request).execute();

    String data = response.body().string();
    Charset cs = response.body().contentType().charset();
    return new HTMLDocument(data, cs);
}

From source file:de.uni_weimar.m18.backupfestival.network.UnsplashApi.java

License:Apache License

public UnsplashApi() {
    Cache cache = null;//from  w w w  .j  ava 2  s .  c  o m
    OkHttpClient okHttpClient = null;

    try {
        File cacheDir = new File(FestivalApplication.getContext().getCacheDir().getPath(), "pictures.json");
        cache = new Cache(cacheDir, 10 * 1024 * 1024);
        okHttpClient = new OkHttpClient();
        okHttpClient.setCache(cache);
    } catch (Exception e) {
        // TODO: do something meaningful? - File error handling?
    }

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(ENDPOINT)
            .setClient(new OkClient(okHttpClient)).setConverter(new GsonConverter(gson))
            .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    request.addHeader("Cache-Control", "public, max-age=" + 60 * 60 * 4);
                }
            }).build();
    mWebService = restAdapter.create(UnsplashService.class);
}

From source file:de.uni_weimar.m18.backupfestival.network.WpJsonApi.java

License:Apache License

public WpJsonApi() {
    Cache cache = null;//ww w . j a  v  a2  s  .  c om
    OkHttpClient okHttpClient = null;

    try {
        File cacheDir = new File(FestivalApplication.getContext().getCacheDir().getPath(), "data.json");
        cache = new Cache(cacheDir, 10 * 1024 * 1024);
        okHttpClient = new OkHttpClient();
        okHttpClient.setCache(cache);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error during OkHttpClient init: " + e.getMessage());
        // TODO: do something meaningful? - File error handling?
    }

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(ENDPOINT)
            .setClient(new OkClient(okHttpClient)).setConverter(new GsonConverter(gson))
            .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    request.addHeader("Cache-Control", "public, max-age=" + 60 * 60 * 4);
                }
            }).build();
    mWebService = restAdapter.create(WpJsonService.class);
}