Java Code Examples for com.squareup.okhttp.OkHttpClient

The following examples show how to use com.squareup.okhttp.OkHttpClient. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: kayenta   Source File: BackendUpdater.java    License: Apache License 2.0 6 votes vote down vote up
boolean run(
    RetrofitClientFactory retrofitClientFactory,
    ObjectMapper objectMapper,
    OkHttpClient okHttpClient) {
  RemoteService remoteService = new RemoteService();
  remoteService.setBaseUrl(uri);
  BackendsRemoteService backendsRemoteService =
      retrofitClientFactory.createClient(
          BackendsRemoteService.class,
          new JacksonConverter(objectMapper),
          remoteService,
          okHttpClient);
  try {
    List<Backend> backends = AuthenticatedRequest.allowAnonymous(backendsRemoteService::fetch);
    backendDatabase.update(backends);
  } catch (RetrofitError e) {
    log.warn("While fetching atlas backends from " + uri, e);
    return succeededAtLeastOnce;
  }
  succeededAtLeastOnce = true;
  return true;
}
 
Example 2
/**
 * Builds a suitable set of peer discoveries. Will query them in parallel before producing a merged response.
 * If specific services are required, DNS is not used as the protocol can't handle it.
 * @param params Network to use.
 * @param services Required services as a bitmask, e.g. {@link VersionMessage#NODE_NETWORK}.
 */
public static MultiplexingDiscovery forServices(NetworkParameters params, long services) {
    List<PeerDiscovery> discoveries = Lists.newArrayList();
    HttpDiscovery.Details[] httpSeeds = params.getHttpSeeds();
    if (httpSeeds != null) {
        OkHttpClient httpClient = new OkHttpClient();
        for (HttpDiscovery.Details httpSeed : httpSeeds)
            discoveries.add(new HttpDiscovery(params, httpSeed, httpClient));
    }
    // Also use DNS seeds if there is no specific service requirement
    if (services == 0) {
        String[] dnsSeeds = params.getDnsSeeds();
        if (dnsSeeds != null)
            for (String dnsSeed : dnsSeeds)
                discoveries.add(new DnsSeedDiscovery(params, dnsSeed));
    }
    return new MultiplexingDiscovery(params, discoveries);
}
 
Example 3
Source Project: reader   Source File: HttpEngine.java    License: MIT License 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 *     creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 *     immediately prior to this request/response pair, such as a same-host
 *     redirect. This engine assumes ownership of the connection and must
 *     release it when it is unneeded.
 */
public HttpEngine(OkHttpClient client, Policy policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.client = client;
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 4
@SuppressWarnings("unchecked")
@Test
public void runtimeExceptionThrownForIoExceptionDuringHttpCommunication() throws Exception {
  // Arrange
  OkHttpClient mockHttpClient = mock(OkHttpClient.class);
  RangeReceiver mockReceiver = mock(RangeReceiver.class);
  RangeTransferListener listener = mock(RangeTransferListener.class);
  when(listener.newTransfer(any(List.class))).thenReturn(mock(HttpTransferListener.class));
  List<ContentRange> ranges = this.createSomeRanges(1);
  URI url = new URI("http://host/someurl");
  IOException expected = new IOException("IO");
  Call mockCall = mock(Call.class);
  when(mockCall.execute()).thenThrow(expected);
  when(mockHttpClient.newCall(any(Request.class))).thenReturn(mockCall);

  // Act
  try {
    new HttpClient(mockHttpClient).partialGet(url, ranges, Collections.<String, Credentials>emptyMap(), mockReceiver,
        listener);
  } catch (IOException exception) {

    // Assert
    assertEquals("IO", exception.getMessage());
  }
}
 
Example 5
Source Project: open   Source File: MapFragmentTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldUse10MegResponseCache() throws Exception {
    Map map = mapFragment.getMap();
    TileLayer baseLayer = field("mBaseLayer").ofType(TileLayer.class).in(map).get();
    UrlTileSource tileSource =
            (UrlTileSource) field("mTileSource").
                    ofType(TileSource.class).in(baseLayer).get();
    HttpEngine.Factory engine = field("mHttpFactory").
            ofType(HttpEngine.Factory.class).in(tileSource).get();
    OkHttpClient client = field("mClient").ofType(OkHttpClient.class).in(engine).get();

    HttpResponseCache cache =
            (HttpResponseCache) field("responseCache").
                    ofType(OkResponseCache.class).in(client).get();
    assertThat(cache.getMaxSize()).isEqualTo(MapFragment.CACHE_SIZE);
}
 
Example 6
Source Project: OkDownload   Source File: OkHttpClientManager.java    License: Apache License 2.0 6 votes vote down vote up
public static OkHttpClient getsInstance() {
    if (sInstance == null) {
        synchronized (OkHttpClientManager.class) {
            if (sInstance == null) {
                sInstance = new com.squareup.okhttp.OkHttpClient();
                // cookie enabled
                sInstance.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
                // timeout reading data from the host
                sInstance.setReadTimeout(15, TimeUnit.SECONDS);
                // timeout connection host
                sInstance.setConnectTimeout(20, TimeUnit.SECONDS);
            }
        }
    }
    return sInstance;
}
 
Example 7
Source Project: L.TileLayer.Cordova   Source File: HttpEngine.java    License: MIT License 6 votes vote down vote up
/**
 * @param requestHeaders the client's supplied request headers. This class
 *     creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 *     immediately prior to this request/response pair, such as a same-host
 *     redirect. This engine assumes ownership of the connection and must
 *     release it when it is unneeded.
 */
public HttpEngine(OkHttpClient client, Policy policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.client = client;
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
Example 8
Source Project: http2-examples   Source File: OkHttpClientExample.java    License: Apache License 2.0 6 votes vote down vote up
private static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, TRUST_ALL_CERTS, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier((hostname, session) -> true);

        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source Project: Mover   Source File: Constants.java    License: Apache License 2.0 5 votes vote down vote up
public static void init(Context context){
    //TODO initialize singletons or global instance of class
    Configuration config = new Configuration.Builder(context)
            .injector((WatchMeApplication) context)
            .build();

    sJobManager = new JobManager(context, config);

    sOkHttpClient = new OkHttpClient();
    sOkClient = new OkClient(sOkHttpClient);

    sEventBus = new Bus();
}
 
Example 10
Source Project: FloatingSearchView   Source File: RetrofitModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides
Retrofit.Builder provideRetrofitBuilder(OkHttpClient httpClient, Converter.Factory factory) {
    return new Retrofit.Builder()
            .client(httpClient)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(factory);
}
 
Example 11
Source Project: DoraemonKit   Source File: OkHttpDownloader.java    License: Apache License 2.0 5 votes vote down vote up
private static OkHttpClient defaultOkHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(Utils.DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(Utils.DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(Utils.DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    return client;
}
 
Example 12
Source Project: Auth0.Android   Source File: OkHttpClientFactoryTest.java    License: MIT License 5 votes vote down vote up
@Test
@Config(sdk = 22)
public void shouldEnableLoggingTLS12Enforced_postLollipopTLS12NoEffect() {
    List list = generateInterceptorsMockList(mockClient);
    OkHttpClient client = factory.modifyClient(mockClient, true, true, 0, 0, 0);
    verifyLoggingEnabled(client, list);
    verifyTLS12NotEnforced(client);
}
 
Example 13
Source Project: OkDownload   Source File: MyApplication.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    Stetho.initializeWithDefaults(this);
    OkHttpClient client = new OkHttpClient();
    client.networkInterceptors().add(new StethoInterceptor());
}
 
Example 14
public HttpURLConnectionImpl(URL url, OkHttpClient client, OkResponseCache responseCache,
    Set<Route> failedRoutes) {
  super(url);
  this.followProtocolRedirects = client.getFollowProtocolRedirects();
  this.failedRoutes = failedRoutes;
  this.requestedProxy = client.getProxy();
  this.proxySelector = client.getProxySelector();
  this.cookieHandler = client.getCookieHandler();
  this.connectionPool = client.getConnectionPool();
  this.sslSocketFactory = client.getSslSocketFactory();
  this.hostnameVerifier = client.getHostnameVerifier();
  this.responseCache = responseCache;
}
 
Example 15
Source Project: kayenta   Source File: RetrofitClientFactory.java    License: Apache License 2.0 5 votes vote down vote up
public <T> T createClient(
    Class<T> type,
    Converter converter,
    RemoteService remoteService,
    OkHttpClient okHttpClient,
    String username,
    String password,
    String usernamePasswordFile)
    throws IOException {
  String baseUrl = remoteService.getBaseUrl();

  baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;

  Endpoint endpoint = newFixedEndpoint(baseUrl);

  if (!(StringUtils.isEmpty(username)
      && StringUtils.isEmpty(password)
      && StringUtils.isEmpty(usernamePasswordFile))) {
    okHttpClient = createAuthenticatedClient(username, password, usernamePasswordFile);
  }

  Slf4jRetrofitLogger logger = createRetrofitLogger.apply(type);

  return new RestAdapter.Builder()
      .setEndpoint(endpoint)
      .setClient(new OkClient(okHttpClient))
      .setConverter(converter)
      .setLogLevel(RestAdapter.LogLevel.valueOf(retrofitLogLevel))
      .setLog(logger)
      .build()
      .create(type);
}
 
Example 16
Source Project: xDrip-plus   Source File: ShareRest.java    License: GNU General Public License v3.0 5 votes vote down vote up
public ShareRest(Context context, OkHttpClient okHttpClient) {

        try {
            OkHttpClient httpClient = okHttpClient != null ? okHttpClient : getOkHttpClient();

            if (httpClient == null) httpClient = getOkHttpClient(); // try again on failure
            // if fails second time we've got big problems

            sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            Gson gson = new GsonBuilder()
                    .excludeFieldsWithoutExposeAnnotation()
                    .create();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(sharedPreferences.getBoolean("dex_share_us_acct", true) ? US_SHARE_BASE_URL : NON_US_SHARE_BASE_URL)
                    .client(httpClient)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
            dexcomShareApi = retrofit.create(DexcomShare.class);
            sessionId = sharedPreferences.getString("dexcom_share_session_id", null);
            username = sharedPreferences.getString("dexcom_account_name", null);
            password = sharedPreferences.getString("dexcom_account_password", null);
            serialNumber = sharedPreferences.getString("share_key", null);
            if (sharedPreferences.getBoolean("engineering_mode", false)) {
                final String share_test_key = sharedPreferences.getString("share_test_key", "").trim();
                if (share_test_key.length() > 4) serialNumber = share_test_key;
            }
            sharedPreferences.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
            if ("".equals(sessionId)) // migrate previous empty sessionIds to null;
                sessionId = null;
        } catch (IllegalStateException e) {
            Log.wtf(TAG, "Illegal state exception: " + e);
        }
    }
 
Example 17
Source Project: kayenta   Source File: DatadogConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static DatadogRemoteService createDatadogRemoteService(
    RetrofitClientFactory retrofitClientFactory,
    ObjectMapper objectMapper,
    RemoteService endpoint,
    OkHttpClient okHttpClient) {

  return retrofitClientFactory.createClient(
      DatadogRemoteService.class, new JacksonConverter(objectMapper), endpoint, okHttpClient);
}
 
Example 18
Source Project: AsyncOkHttpClient   Source File: AsyncHttpRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
    * Constructs a new instance of AsyncHttpRequest
    * @param client the client to execute the given request
    * @param responseHandler the callback for fire responses like success and error
    * @param params the request parameters for GET, POST...
    * @param request the model that contains the request method and headers
    */
public AsyncHttpRequest(OkHttpClient client, AsyncHttpResponse responseHandler, 
		RequestParams params, RequestModel request) {
	mResponse = responseHandler;
	mClient = client.open(request.getURL());
	mRequest = request;
	mRequestParams = params;
}
 
Example 19
Source Project: Auth0.Android   Source File: OkHttpClientFactoryTest.java    License: MIT License 5 votes vote down vote up
@Test
@Config(sdk = 21)
public void shouldEnableLoggingTLS12NotEnforced() {
    List list = generateInterceptorsMockList(mockClient);
    OkHttpClient client = factory.modifyClient(mockClient, true, false, 0, 0, 0);
    verifyLoggingEnabled(client, list);
    verifyTLS12NotEnforced(client);
}
 
Example 20
Source Project: githot   Source File: DataModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
FirService provideFirService(Gson gson, OkHttpClient okHttpClient, ErrorHandler errorHandler) {
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setErrorHandler(errorHandler)
            .setClient(new OkClient(okHttpClient))
            .setConverter(new GsonConverter(gson))
            .setLogLevel(RestAdapter.LogLevel.BASIC)
            .setEndpoint("http://api.fir.im")
            .build();
    return restAdapter.create(FirService.class);
}
 
Example 21
Source Project: jus   Source File: OkHttpStack.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public NetworkResponse performRequest(Request<?> request, Headers
        additionalHeaders, ByteArrayPool byteArrayPool) throws IOException {

    //clone to be able to set timeouts per call
    OkHttpClient client = this.client.clone();
    client.setConnectTimeout(request.getRetryPolicy().getCurrentConnectTimeout(), TimeUnit
            .MILLISECONDS);
    client.setReadTimeout(request.getRetryPolicy().getCurrentReadTimeout(), TimeUnit
            .MILLISECONDS);
    com.squareup.okhttp.Request okRequest = new com.squareup.okhttp.Request.Builder()
            .url(request.getUrlString())
            .headers(JusOk.okHeaders(request.getHeaders(), additionalHeaders))
            .tag(request.getTag())
            .method(request.getMethod(), JusOk.okBody(request.getNetworkRequest()))
            .build();

    long requestStart = System.nanoTime();

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

    byte[] data = null;
    if (NetworkDispatcher.hasResponseBody(request.getMethod(), response.code())) {
        data = getContentBytes(response.body().source(),
                byteArrayPool, (int) response.body().contentLength());
    } else {
        // Add 0 byte response as a way of honestly representing a
        // no-content request.
        data = new byte[0];
    }
    return new NetworkResponse.Builder()
            .setHeaders(JusOk.jusHeaders(response.headers()))
            .setStatusCode(response.code())
            .setBody(data)
            .setNetworkTimeNs(System.nanoTime() - requestStart)
            .build();
}
 
Example 22
Source Project: AndroidNetwork   Source File: RemoteService.java    License: MIT License 5 votes vote down vote up
public static synchronized RemoteService getInstance() {
    if (service == null) {
        service = new RemoteService();
        mOkHttpClient = new OkHttpClient();

        //设置超时时间
        //参见:OkHttp3超时设置和超时异常捕获
        //http://blog.csdn.net/do168/article/details/51848895
        mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
    }
    return service;
}
 
Example 23
public static Picasso getInstance(Context context, boolean changeCredentials) {
    if (mPicasso == null || changeCredentials) {
        OkHttpClient client = RepoManager.provideOkHttpClient(
                DhisController.getInstance().getUserCredentials(), context);
        mPicasso = new Picasso.Builder(context)
                .downloader(new OkHttpDownloader(client))
                .build();
        mPicasso.setIndicatorsEnabled(false);
        mPicasso.setLoggingEnabled(false);
    }

    return mPicasso;
}
 
Example 24
Source Project: NewXmPluginSDK   Source File: TestCaseActivity.java    License: Apache License 2.0 5 votes vote down vote up
public Response uploadFile(String url, String filePath) throws IOException {
    Log.d("test", "url:" + url);
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(30, TimeUnit.SECONDS);
    client.setReadTimeout(15, TimeUnit.SECONDS);
    client.setWriteTimeout(30, TimeUnit.SECONDS);
    Request request = new Request.Builder()
            .url(url)
            .put(RequestBody.create(MediaType.parse(""), new File(filePath)))
            .build();
    return client.newCall(request).execute();
}
 
Example 25
Source Project: AndroidNetwork   Source File: RemoteService.java    License: MIT License 5 votes vote down vote up
public static synchronized RemoteService getInstance() {
    if (service == null) {
        service = new RemoteService();
        mOkHttpClient = new OkHttpClient();
    }
    return service;
}
 
Example 26
Source Project: AndroidNetwork   Source File: RemoteService.java    License: MIT License 5 votes vote down vote up
public static synchronized RemoteService getInstance() {
    if (service == null) {
        service = new RemoteService();
        mOkHttpClient = new OkHttpClient();
    }
    return service;
}
 
Example 27
Source Project: OkDownload   Source File: OkDownloadTask.java    License: Apache License 2.0 5 votes vote down vote up
public OkDownloadTask(Context context, OkHttpClient okHttpClient, OkDatabaseHelp okDatabaseHelp) {
    if (context != null) {
        mContext = context;
        mOkDatabaseHelp = okDatabaseHelp;
        if (mOkDatabaseHelp == null) {
            mOkDatabaseHelp = OkDatabaseHelp.getInstance(mContext);
        }
    }
    if (okHttpClient != null) {
        mOkHttpClient = okHttpClient;
    } else {
        mOkHttpClient = OkHttpClientManager.getsInstance();
    }
}
 
Example 28
Source Project: SoBitmap   Source File: NetworkHunter.java    License: Apache License 2.0 5 votes vote down vote up
NetworkHunter() {
    super();
    client = new OkHttpClient();
    client.setConnectTimeout(15000, TimeUnit.MILLISECONDS);
    client.setReadTimeout(20000, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(20000, TimeUnit.MILLISECONDS);
}
 
Example 29
public boolean connect(String url) {
  OkHttpClient httpClient = new OkHttpClient();
  Request request = new Request.Builder().url(url).addHeader("sec-websocket-protocol", "echo-protocol").build();
  WebSocketCall.create(httpClient, request).enqueue(new WXWebSocketListener(url));

  return true;
}
 
Example 30
Source Project: mirror   Source File: MirrorApplication.java    License: Apache License 2.0 5 votes vote down vote up
private void initializeOkHttp() {
    Cache cache = new Cache(new File(getCacheDir(), "http"), 25 * 1024 * 1024);

    mOkHttpClient = new OkHttpClient();
    mOkHttpClient.setCache(cache);
    mOkHttpClient.setConnectTimeout(30, SECONDS);
    mOkHttpClient.setReadTimeout(30, SECONDS);
    mOkHttpClient.setWriteTimeout(30, SECONDS);
}