List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient
public OkHttpClient()
From source file:cn.wochu.wh.net.OkHttpClientManager.java
License:Apache License
private OkHttpClientManager() { mOkHttpClient = new OkHttpClient(); //cookie enabled mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)); mDelivery = new Handler(Looper.getMainLooper()); mGson = new Gson(); }
From source file:co.paralleluniverse.fibers.okhttp.test.utils.original.SocksProxyTest.java
License:Apache License
@Test public void proxy() throws Exception { server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("def")); OkHttpClient client = new OkHttpClient().setProxy(socksProxy.proxy()); Request request1 = new Request.Builder().url(server.url("/")).build(); Response response1 = client.newCall(request1).execute(); assertEquals("abc", response1.body().string()); Request request2 = new Request.Builder().url(server.url("/")).build(); Response response2 = client.newCall(request2).execute(); assertEquals("def", response2.body().string()); // The HTTP calls should share a single connection. assertEquals(1, socksProxy.connectionCount()); }
From source file:co.paralleluniverse.fibers.okhttp.test.utils.original.SocksProxyTest.java
License:Apache License
@Test public void proxySelector() throws Exception { server.enqueue(new MockResponse().setBody("abc")); ProxySelector proxySelector = new ProxySelector() { @Override//w w w.j ava 2 s. com public List<Proxy> select(URI uri) { return Collections.singletonList(socksProxy.proxy()); } @Override public void connectFailed(URI uri, SocketAddress socketAddress, IOException e) { throw new AssertionError(); } }; OkHttpClient client = new OkHttpClient().setProxySelector(proxySelector); Request request = new Request.Builder().url(server.url("/")).build(); Response response = client.newCall(request).execute(); assertEquals("abc", response.body().string()); assertEquals(1, socksProxy.connectionCount()); }
From source file:co.rsk.rpc.netty.Web3WebSocketServerTest.java
License:Open Source License
@Test public void smokeTest() throws Exception { Web3 web3Mock = mock(Web3.class); String mockResult = "output"; when(web3Mock.web3_sha3(anyString())).thenReturn(mockResult); int randomPort = 9998;//new ServerSocket(0).getLocalPort(); List<ModuleDescription> filteredModules = Collections.singletonList( new ModuleDescription("web3", "1.0", true, Collections.emptyList(), Collections.emptyList())); RskJsonRpcHandler handler = new RskJsonRpcHandler(null, new JacksonBasedRpcSerializer()); JsonRpcWeb3ServerHandler serverHandler = new JsonRpcWeb3ServerHandler(web3Mock, filteredModules); Web3WebSocketServer websocketServer = new Web3WebSocketServer(InetAddress.getLoopbackAddress(), randomPort, handler, serverHandler);//w w w. j a v a2s. c o m websocketServer.start(); OkHttpClient wsClient = new OkHttpClient(); Request wsRequest = new Request.Builder().url("ws://localhost:" + randomPort + "/websocket").build(); WebSocketCall wsCall = WebSocketCall.create(wsClient, wsRequest); CountDownLatch wsAsyncResultLatch = new CountDownLatch(1); CountDownLatch wsAsyncCloseLatch = new CountDownLatch(1); AtomicReference<Exception> failureReference = new AtomicReference<>(); wsCall.enqueue(new WebSocketListener() { private WebSocket webSocket; @Override public void onOpen(WebSocket webSocket, Response response) { wsExecutor.submit(() -> { RequestBody body = RequestBody.create(WebSocket.TEXT, getJsonRpcDummyMessage()); try { this.webSocket = webSocket; this.webSocket.sendMessage(body); this.webSocket.close(1000, null); } catch (IOException e) { failureReference.set(e); } }); } @Override public void onFailure(IOException e, Response response) { failureReference.set(e); } @Override public void onMessage(ResponseBody message) throws IOException { JsonNode jsonRpcResponse = OBJECT_MAPPER.readTree(message.bytes()); assertThat(jsonRpcResponse.at("/result").asText(), is(mockResult)); message.close(); wsAsyncResultLatch.countDown(); } @Override public void onPong(Buffer payload) { } @Override public void onClose(int code, String reason) { wsAsyncCloseLatch.countDown(); } }); if (!wsAsyncResultLatch.await(10, TimeUnit.SECONDS)) { fail("Result timed out"); } if (!wsAsyncCloseLatch.await(10, TimeUnit.SECONDS)) { fail("Close timed out"); } websocketServer.stop(); Exception failure = failureReference.get(); if (failure != null) { failure.printStackTrace(); fail(failure.getMessage()); } }
From source file:co.uk.crowdemotion.ApiClient.java
License:Apache License
public ApiClient() { httpClient = new OkHttpClient(); verifyingSsl = true;/*from w ww. jav a2 s . com*/ 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("api_key", new ApiKeyAuth("header", "Authorization")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); }
From source file:co.waitlisted.ApiClient.java
License:Apache License
public ApiClient() { httpClient = new OkHttpClient(); verifyingSsl = true;// w w w. j a v a 2 s. c o m 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/2.0.0/java"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap<String, Authentication>(); authentications.put("api_key", new ApiKeyAuth("header", "X-API-Key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); }
From source file:com.abiquo.apiclient.RestClient.java
License:Apache License
RestClient(final Authentication authentication, final String baseURL, final String apiVersion, final SSLConfiguration sslConfiguration) { this.json = new Json(); this.baseURL = checkNotNull(baseURL, "baseURL cannot be null"); this.apiVersion = checkNotNull(apiVersion, "apiVersion cannot be null"); client = new OkHttpClient(); client.setReadTimeout(0, TimeUnit.MILLISECONDS); client.networkInterceptors().add(new AuthenticationInterceptor(authentication)); if (sslConfiguration != null) { client.setHostnameVerifier(sslConfiguration.hostnameVerifier()); client.setSslSocketFactory(sslConfiguration.sslContext().getSocketFactory()); }//ww w . j av a 2 s . co m }
From source file:com.adamg.materialtemplate.cloud.module.OkHttpModule.java
License:MIT License
/** * Creates a default OkHttp client with a disk cache of 10 MB * * @param ctx a reference to the Client's {@link Context} * @return the instance of the OkHttp Client used as the transport layer for API calls *///from w ww. j a v a2 s. com static OkHttpClient createOkHttpClient(final Context ctx) { OkHttpClient client = new OkHttpClient(); // Install an HTTP cache in the application cache directory. try { final File cacheDir = new File(ctx.getCacheDir(), "https"); final Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE); client.setCache(cache); } catch (final IOException e) { // Log the error Log.e(TAG, "Unable to install disk cache." + Log.getStackTraceString(e)); } return client; }
From source file:com.adnanbal.fxdedektifi.sample.data.net.ApiConnection.java
License:Apache License
private OkHttpClient createClient() { final OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setReadTimeout(10000, TimeUnit.MILLISECONDS); okHttpClient.setConnectTimeout(15000, TimeUnit.MILLISECONDS); return okHttpClient; }
From source file:com.ae.apps.pnrstatus.service.NetworkService.java
License:Open Source License
private NetworkService() { client = new OkHttpClient(); }