com.squareup.okhttp.OkHttpClient Java Examples

The following examples show how to use com.squareup.okhttp.OkHttpClient. 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 check out the related API usage on the sidebar.
Example #1
Source File: BackendUpdater.java    From kayenta with 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
Source File: OkHttpClientExample.java    From http2-examples with 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 #3
Source File: MultiplexingDiscovery.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #4
Source File: HttpEngine.java    From L.TileLayer.Cordova with 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 #5
Source File: HttpEngine.java    From reader with 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 #6
Source File: MapFragmentTest.java    From open with 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 #7
Source File: HttpClientTest.java    From zsync4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #8
Source File: OkHttpClientManager.java    From OkDownload with 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 #9
Source File: ApiFactory.java    From particle-android with Apache License 2.0 5 votes vote down vote up
private RestAdapter.Builder buildCommonRestAdapterBuilder(Gson gson, OkHttpClient client) {
    return new RestAdapter.Builder()
            .setClient(new OkClient(client))
            .setConverter(new GsonConverter(gson))
            .setEndpoint(getApiUri().toString())
            .setLogLevel(httpLogLevel);
}
 
Example #10
Source File: TestCaseActivity.java    From NewXmPluginSDK with 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 #11
Source File: DataModule.java    From Pioneer with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
Picasso providePicasso(Application app, OkHttpClient client) {
    return new Picasso.Builder(app)
            .downloader(new OkHttpDownloader(client))
            .listener(new Picasso.Listener() {
                @Override public void onImageLoadFailed(Picasso picasso, Uri uri, Exception e) {
                    Timber.e(e, "Failed to load image: %s", uri);
                }
            })
            .build();
}
 
Example #12
Source File: AppModule.java    From RhymeCity with MIT License 5 votes vote down vote up
@Provides
@Singleton
OkHttpClient provideClient() {
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new AuthInterceptor(apiKey));
    return client;
}
 
Example #13
Source File: DataModule.java    From githot with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
ReposTrendingApiService provideTrendingApiService(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://trending.codehub-app.com")
            .build();
    return restAdapter.create(ReposTrendingApiService.class);
}
 
Example #14
Source File: HotRefreshManager.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
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 #15
Source File: RetrofitModule.java    From FloatingSearchView with 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 #16
Source File: NetworkHunter.java    From SoBitmap with 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 #17
Source File: RemoteService.java    From AndroidNetwork with 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 #18
Source File: MirrorApplication.java    From mirror with 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);
}
 
Example #19
Source File: WXOkHttpDispatcher.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
private static OkHttpClient defaultOkHttpClient() {
  OkHttpClient client = new OkHttpClient();
  client.networkInterceptors().add(new OkHttpInterceptor());
  client.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  client.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  client.setWriteTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  return client;
}
 
Example #20
Source File: OkUrlFactory.java    From apiman with Apache License 2.0 5 votes vote down vote up
HttpURLConnection open(URL url, Proxy proxy) {
  String protocol = url.getProtocol();
  OkHttpClient copy = client.clone();

  if (protocol.equals("http")) return new HttpURLConnectionImpl(url, copy);
  if (protocol.equals("https")) return new HttpsURLConnectionImpl(url, copy);
  throw new IllegalArgumentException("Unexpected protocol: " + protocol);
}
 
Example #21
Source File: DataUsageActivity.java    From utexas-utilities with Apache License 2.0 5 votes vote down vote up
@Override
protected Void doInBackground(String... params) {
    String reqUrl = params[0];
    Request request = new Request.Builder()
            .url(reqUrl)
            .build();
    String pagedata;
    OkHttpClient client = UTilitiesApplication.getInstance().getHttpClient();

    try {
        Response response = client.newCall(request).execute();
        pagedata = response.body().string();
    } catch (IOException e) {
        errorMsg = "UTilities could not fetch your % data usage";
        e.printStackTrace();
        cancel(true);
        return null;
    }
    publishProgress(pagedata);

    String regex = "<td>Total / Remaining </td>\\s+<td class=\"qty\">([0-9]+) MB</td>\\s+<td class=\"qty.*?\">([0-9]+) MB</td>";
    Pattern dataUsedPattern = Pattern.compile(regex, Pattern.MULTILINE);
    Matcher dataUsedMatcher = dataUsedPattern.matcher(pagedata);
    int total, remaining;
    if (dataUsedMatcher.find()) {
        total = Integer.parseInt(dataUsedMatcher.group(1));
        remaining = Integer.parseInt(dataUsedMatcher.group(2));
        totalUsed = Integer.toString(total - remaining);
        percentUsed = (total - remaining) / (double) total;
        return null;
    } else {
        errorMsg = "UTilities could not find your % data usage";
        cancel(true);
        return null;
    }
}
 
Example #22
Source File: WaspTest.java    From wasp with Apache License 2.0 5 votes vote down vote up
public WaspTest() throws Exception {
  File cacheDir = new File(context.getCacheDir(), "volley");
  Network network = new BasicNetwork(new OkHttpStack(new OkHttpClient()));
  ResponseDelivery delivery = new ExecutorDelivery(executor);
  requestQueue = new RequestQueue(new DiskBasedCache(cacheDir), network, 4, delivery);
  requestQueue.start();

  server.start();
}
 
Example #23
Source File: RemoteService.java    From AndroidNetwork with 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 #24
Source File: OkDownloadTask.java    From OkDownload with 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 #25
Source File: PicassoProvider.java    From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #26
Source File: RemoteService.java    From AndroidNetwork with 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 #27
Source File: OkHttpStack.java    From jus with 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 #28
Source File: DataModule.java    From githot with 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 #29
Source File: OkHttpClientFactoryTest.java    From Auth0.Android with 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 #30
Source File: AsyncHttpRequest.java    From AsyncOkHttpClient with 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;
}