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:mobi.lab.sample_event_logging_library.service.LogPostService.java

License:Open Source License

@Override
public void onCreate() {
    super.onCreate();
    //TODO: starting from Android 5.0 we could use JobScheduler (currently not in support libraries)
    handler = new Handler();
    handler.postDelayed(timedRunnable, Config.MAX_TIME_INTERVAL_BETWEEN_REQUESTS);
    logEventsForRequest = new ArrayList<>();

    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override//from  w ww  . j  av a2 s . c o m
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Log.d(TAG, String.format("\n\nrequest:%s\nheaders:%s\n" + "url:%s", request.body().toString(),
                    request.headers(), request.httpUrl().toString()));
            return chain.proceed(request);
        }
    });

    Retrofit retrofit = new Retrofit.Builder().baseUrl(Network.BASE_API_URL)
            .addConverterFactory(GsonConverterFactory.create()).client(client).build();

    logEventService = retrofit.create(LogEventRequest.class);

    if (checkCallingOrSelfPermission(
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && checkCallingOrSelfPermission(
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        //TODO: ask for permission if not given
        Log.d(TAG, "location permission not granted");
        isLocationServicesEnabled = false;
        return;
    }
    isLocationServicesEnabled = true;
    final LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    Log.d(TAG, "requesting user location");
    locationManager.requestLocationUpdates(Config.LOCATION_UPDATES_MIN_TIME,
            Config.LOCATION_UPDATES_MIN_DISTANCE, criteria, this, null);
}

From source file:my.test.support.ApiClient.java

License:Apache License

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

    verifyingSsl = true;// 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");

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

From source file:name.dlazerka.androidupload.Application.java

License:Apache License

@Override
public void onCreate() {
    // Not visible by default, set "adb shell setprop log.tag.MyAppTag VERBOSE" to configure.
    logger.trace("onCreate");

    super.onCreate();

    okHttpClient = new OkHttpClient();
}

From source file:net.callmeike.android.simplesync.net.NetModule.java

License:Apache License

static OkHttpClient createOkHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, SECONDS);
    client.setReadTimeout(10, SECONDS);/*from  w w w .  ja  va  2  s . com*/
    client.setWriteTimeout(10, SECONDS);
    return client;
}

From source file:net.codestory.rest.RestResponse.java

License:Apache License

static RestResponse call(String url, Function<OkHttpClient, OkHttpClient> configureClient,
        Function<Request.Builder, Request.Builder> configureRequest) throws IOException {
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(ACCEPT_ALL);

    Request.Builder request = configureRequest.apply(new Request.Builder().url(url));
    OkHttpClient client = configureClient.apply(new OkHttpClient().setCookieHandler(cookieManager));

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

    return new RestResponse(cookieManager, response);
}

From source file:net.fred.feedex.utils.NetworkUtils.java

License:Open Source License

public static HttpURLConnection setupConnection(URL url) throws IOException {
    HttpURLConnection connection = new OkUrlFactory(new OkHttpClient()).open(url);

    connection.setDoInput(true);/* w w  w  .j a  v a2 s.  com*/
    connection.setDoOutput(false);
    connection.setRequestProperty("User-agent", "Mozilla/5.0 (compatible) AppleWebKit Chrome Safari"); // some feeds need this to work properly
    connection.setConnectTimeout(30000);
    connection.setReadTimeout(30000);
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(true);
    connection.setRequestProperty("accept", "*/*");

    COOKIE_MANAGER.getCookieStore().removeAll(); // Cookie is important for some sites, but we clean them each times
    connection.connect();

    return connection;
}

From source file:net.iquestria.java.iQuestria.java

public static void getUserById(Integer id, UserHandler callback) {
    OkHttpClient client = new OkHttpClient();
    Request req = new Request.Builder().url(API_BASE + "/users/" + id + ".json").build();
    UserCallback userCallback = new UserCallback(callback);
    client.newCall(req).enqueue(userCallback);
}

From source file:net.iquestria.java.iQuestria.java

public static void getWorkById(Integer id, WorkHandler callback) {
    OkHttpClient client = new OkHttpClient();
    Request req = new Request.Builder().url(API_BASE + "/works/" + id + ".json").build();
    WorkCallback workCallback = new WorkCallback(callback);
    client.newCall(req).enqueue(workCallback);
}

From source file:net.ltgt.resteasy.client.okhttp.OkHttpClientEngineTest.java

License:Apache License

@Before
public void configureClient() {
    okHttpClient = new OkHttpClient();
    okHttpClient.interceptors().add(new Interceptor() {
        @Override/*  w  w w .  j  av  a2s.  c  om*/
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            return chain.proceed(chain.request().newBuilder().tag(TAG).build());
        }
    });
    client = new ResteasyClientBuilder().httpEngine(new OkHttpClientEngine(new OkHttpClient())).build();
}

From source file:net.protyposis.android.mediaplayer.dash.DashParser.java

License:Open Source License

/**
 * Parses an MPD XML file. This needs to be executed off the main thread, else a
 * NetworkOnMainThreadException gets thrown.
 * @param source the URl of an MPD XML file
 * @return a MPD object//from w w  w. java2  s  . com
 * @throws android.os.NetworkOnMainThreadException if executed on the main thread
 */
public MPD parse(UriSource source) throws DashParserException {
    MPD mpd = null;
    OkHttpClient httpClient = new OkHttpClient();

    Headers.Builder headers = new Headers.Builder();
    if (source.getHeaders() != null && !source.getHeaders().isEmpty()) {
        for (String name : source.getHeaders().keySet()) {
            headers.add(name, source.getHeaders().get(name));
        }
    }

    Uri uri = source.getUri();

    Request.Builder request = new Request.Builder().url(uri.toString()).headers(headers.build());

    try {
        Response response = httpClient.newCall(request.build()).execute();
        if (!response.isSuccessful()) {
            throw new IOException("error requesting the MPD");
        }

        // Determine this MPD's default BaseURL by removing the last path segment (which is the MPD file)
        Uri baseUrl = Uri.parse(uri.toString().substring(0, uri.toString().lastIndexOf("/") + 1));

        // Get the current datetime from the server for live stream time syncing
        serverDate = response.headers().getDate("Date");

        // Parse the MPD file
        mpd = parse(response.body().byteStream(), baseUrl);
    } catch (IOException e) {
        Log.e(TAG, "error downloading the MPD", e);
        throw new DashParserException("error downloading the MPD", e);
    } catch (XmlPullParserException e) {
        Log.e(TAG, "error parsing the MPD", e);
        throw new DashParserException("error parsing the MPD", e);
    }

    return mpd;
}