List of usage examples for com.squareup.okhttp Request.Builder Request.Builder
Request.Builder
From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
@Test public void networkInterceptorModifiedRequestIsReturned() throws IOException { server.enqueue(new MockResponse()); Interceptor modifyHeaderInterceptor = new Interceptor() { @Override/* ww w .ja v a 2s. c om*/ public Response intercept(Chain chain) throws IOException { return chain .proceed(chain.request().newBuilder().header("User-Agent", "intercepted request").build()); } }; client.networkInterceptors().add(modifyHeaderInterceptor); Request request = new Request.Builder().url(server.url("/")).header("User-Agent", "user request").build(); Response response = client.newCall(request).execute(); assertNotNull(response.request().header("User-Agent")); assertEquals("user request", response.request().header("User-Agent")); assertEquals("intercepted request", response.networkResponse().request().header("User-Agent")); }
From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
/** * When an interceptor throws an unexpected exception, asynchronous callers are left hanging. The * exception goes to the uncaught exception handler. * * TODO(jwilson): test that resources are not leaked when this happens. *///from w w w . ja v a2 s .c o m private void interceptorThrowsRuntimeExceptionAsynchronous(List<Interceptor> interceptors) throws Exception { interceptors.add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { throw new RuntimeException("boom!"); } }); ExceptionCatchingExecutor executor = new ExceptionCatchingExecutor(); client.setDispatcher(new Dispatcher(executor)); Request request = new Request.Builder().url(server.url("/")).build(); client.newCall(request).enqueue(callback); assertEquals("boom!", executor.takeException().getMessage()); }
From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
@Ignore @Test//from w w w . j av a 2 s . c om public void applicationInterceptorReturnsNull() throws Exception { server.enqueue(new MockResponse()); Interceptor interceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { chain.proceed(chain.request()); return null; } }; client.interceptors().add(interceptor); ExceptionCatchingExecutor executor = new ExceptionCatchingExecutor(); client.setDispatcher(new Dispatcher(executor)); Request request = new Request.Builder().url(server.url("/")).build(); try { client.newCall(request).execute(); fail(); } catch (NullPointerException expected) { assertEquals("application interceptor " + interceptor + " returned null", expected.getMessage()); } }
From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
@Ignore @Test/*from w w w .j av a 2 s . c o m*/ public void networkInterceptorReturnsNull() throws Exception { server.enqueue(new MockResponse()); Interceptor interceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { chain.proceed(chain.request()); return null; } }; client.networkInterceptors().add(interceptor); ExceptionCatchingExecutor executor = new ExceptionCatchingExecutor(); client.setDispatcher(new Dispatcher(executor)); Request request = new Request.Builder().url(server.url("/")).build(); try { client.newCall(request).execute(); fail(); } catch (NullPointerException expected) { assertEquals("network interceptor " + interceptor + " returned null", expected.getMessage()); } }
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);//ww w . jav a2 s . c om 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:com.android.codg.rentadeactivos.TestWebServer.java
public String getString1(String metodo, RequestBody formBody) { try {/*from www . j a v a 2 s . co m*/ URL url = new URL("http://192.168.0.16:5000/" + metodo); Request request = new Request.Builder().url(url).post(formBody).build(); Response response = webClient.newCall(request).execute();//Aqui obtiene la respuesta en dado caso si hayas pues un return en python String response_string = response.body().string();//y este seria el string de las respuesta //System.out.println(response_string); return response_string; } catch (MalformedURLException ex) { return "aldo"; } catch (Exception ex) { String mensaje = ex.toString(); return mensaje; } }
From source file:com.apothesource.pillfill.network.PFNetworkManager.java
License:Open Source License
public static String doPinnedGetForUrl(String url) throws IOException { OkHttpClient client = getPinnedPFHttpClient(); Request.Builder requestBuilder = new Request.Builder().url(url); Response response = client.newCall(requestBuilder.build()).execute(); return response.body().string(); }
From source file:com.apothesource.pillfill.network.PFNetworkManager.java
License:Open Source License
public static String doPinnedGetForUrl(String url, String authToken) throws IOException { OkHttpClient client = getPinnedPFHttpClient(); Request.Builder requestBuilder = new Request.Builder().url(url); if (authToken != null) requestBuilder = requestBuilder.addHeader("Bearer", authToken); Response response = client.newCall(requestBuilder.build()).execute(); return response.body().string(); }
From source file:com.brq.wallet.bitid.BitIdAuthenticator.java
License:Microsoft Reference Source License
protected Request getRequest(SignedMessage signature) { MediaType jsonType = MediaType.parse("application/json; charset=utf-8"); String jsonString = request.getCallbackJson(address, signature).toString(); RequestBody body = RequestBody.create(jsonType, jsonString); String url = request.getCallbackUri(); return new Request.Builder().url(url).post(body).build(); }
From source file:com.frostwire.util.http.OKHTTPClient.java
License:Open Source License
@Override public int head(String url, int connectTimeoutInMillis, Map<String, List<String>> outputHeaders) throws IOException { final OkHttpClient okHttpClient = newOkHttpClient(); okHttpClient.setConnectTimeout(connectTimeoutInMillis, TimeUnit.MILLISECONDS); okHttpClient.setFollowRedirects(false); Request req = new Request.Builder().url(url).header("User-Agent", DEFAULT_USER_AGENT).head().build(); Response resp = okHttpClient.newCall(req).execute(); copyMultiMap(resp.headers().toMultimap(), outputHeaders); return resp.code(); }