List of usage examples for com.squareup.okhttp RequestBody create
public static RequestBody create(final MediaType contentType, final File file)
From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
@Test public void networkInterceptorsCanChangeRequestMethodFromGetToPost() throws Exception { server.enqueue(new MockResponse()); client.networkInterceptors().add(new Interceptor() { @Override/*from w w w . j av a 2 s. c om*/ public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); MediaType mediaType = MediaType.parse("text/plain"); RequestBody body = RequestBody.create(mediaType, "abc"); return chain.proceed(originalRequest.newBuilder().method("POST", body) .header("Content-Type", mediaType.toString()) .header("Content-Length", Long.toString(body.contentLength())).build()); } }); Request request = new Request.Builder().url(server.url("/")).get().build(); client.newCall(request).execute(); RecordedRequest recordedRequest = server.takeRequest(); assertEquals("POST", recordedRequest.getMethod()); assertEquals("abc", recordedRequest.getBody().readUtf8()); }
From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
private void rewriteRequestToServer(List<Interceptor> interceptors) throws Exception { server.enqueue(new MockResponse()); interceptors.add(new Interceptor() { @Override//from w ww . java 2 s .com public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); return chain.proceed(originalRequest.newBuilder().method("POST", uppercase(originalRequest.body())) .addHeader("OkHttp-Intercepted", "yep").build()); } }); Request request = new Request.Builder().url(server.url("/")).addHeader("Original-Header", "foo") .method("PUT", RequestBody.create(MediaType.parse("text/plain"), "abc")).build(); client.newCall(request).execute(); RecordedRequest recordedRequest = server.takeRequest(); assertEquals("ABC", recordedRequest.getBody().readUtf8()); assertEquals("foo", recordedRequest.getHeader("Original-Header")); assertEquals("yep", recordedRequest.getHeader("OkHttp-Intercepted")); assertEquals("POST", recordedRequest.getMethod()); }
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);/* www .j a v a 2 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.abiquo.apiclient.RestClient.java
License:Apache License
public <T extends SingleResourceTransportDto> T post(final String uri, final String accept, final String contentType, final SingleResourceTransportDto body, final Class<T> returnClass) { try {//from w w w. j a v a 2s . co m RequestBody requestBody = RequestBody.create(MediaType.parse(withVersion(contentType)), json.write(body)); Request request = new Request.Builder().url(absolute(uri)) .addHeader(HttpHeaders.ACCEPT, withVersion(accept)).post(requestBody).build(); return execute(request, returnClass); } catch (IOException ex) { throw Throwables.propagate(ex); } }
From source file:com.abiquo.apiclient.RestClient.java
License:Apache License
public <T extends SingleResourceTransportDto> T post(final String uri, final String accept, final String contentType, final SingleResourceTransportDto body, final TypeToken<T> returnType) { try {// w w w .ja va 2 s .co m RequestBody requestBody = RequestBody.create(MediaType.parse(withVersion(contentType)), json.write(body)); Request request = new Request.Builder().url(absolute(uri)) .addHeader(HttpHeaders.ACCEPT, withVersion(accept)).post(requestBody).build(); return execute(request, returnType); } catch (IOException ex) { throw Throwables.propagate(ex); } }
From source file:com.abiquo.apiclient.RestClient.java
License:Apache License
public <T extends SingleResourceTransportDto> T post(final String uri, final String accept, final String contentType, final String body, final Class<T> returnClass) { try {/*from w ww .j a v a 2 s .c o m*/ RequestBody requestBody = RequestBody.create(MediaType.parse(withVersion(contentType)), body); Request request = new Request.Builder().url(absolute(uri)) .addHeader(HttpHeaders.ACCEPT, withVersion(accept)).post(requestBody).build(); return execute(request, returnClass); } catch (IOException ex) { throw Throwables.propagate(ex); } }
From source file:com.abiquo.apiclient.RestClient.java
License:Apache License
public <T extends SingleResourceTransportDto> T put(final String uri, final String accept, final String contentType, final SingleResourceTransportDto body, final Class<T> returnClass) { try {// w w w.ja va 2s.c o m RequestBody requestBody = RequestBody.create(MediaType.parse(withVersion(contentType)), json.write(body)); Request request = new Request.Builder().url(absolute(uri)) .addHeader(HttpHeaders.ACCEPT, withVersion(accept)).put(requestBody).build(); return execute(request, returnClass); } catch (IOException ex) { throw Throwables.propagate(ex); } }
From source file:com.abiquo.apiclient.RestClient.java
License:Apache License
public <T extends SingleResourceTransportDto> T put(final String uri, final String accept, final String contentType, final SingleResourceTransportDto body, final TypeToken<T> returnType) { try {/*from w w w . ja va 2 s . c o m*/ RequestBody requestBody = RequestBody.create(MediaType.parse(withVersion(contentType)), json.write(body)); Request request = new Request.Builder().url(absolute(uri)) .addHeader(HttpHeaders.ACCEPT, withVersion(accept)).put(requestBody).build(); return execute(request, returnType); } catch (IOException ex) { throw Throwables.propagate(ex); } }
From source file:com.abiquo.apiclient.RestClient.java
License:Apache License
public void put(final String uri, final String accept, final String contentType, final SingleResourceTransportDto body) { try {/*from w w w .j a va2 s . c om*/ String rawBody = json.write(body); RequestBody requestBody = RequestBody.create(MediaType.parse(withVersion(contentType)), rawBody); Request request = new Request.Builder().url(absolute(uri)) .addHeader(HttpHeaders.ACCEPT, withVersion(accept)).put(requestBody).build(); execute(request, (Class<?>) null); } catch (IOException ex) { throw Throwables.propagate(ex); } }
From source file:com.afrisoftech.funsoft.mobilepay.MobilePayAPI.java
public void sendPaymentRequest(String accessToken) { OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/json"); String message = null;/*from w w w . j a v a 2 s. co m*/ JSONObject json = new JSONObject(); try { json.put("InitiatorName", "Charles Waweru"); json.put("SecurityCredential", this.encryptInitiatorPassword("cert.cer", "3414")); json.put("CommandID", "CustomerPayBillOnline"); json.put("Amount", "10"); json.put("PartyA", "254714433693"); json.put("PartyB", "881100"); json.put("Remarks", "Testing Rest API"); json.put("QueueTimeOutURL", ""); json.put("ResultURL", "https://192.162.85.226:17933/FunsoftWebServices/funsoft/InvoiceService/mpesasettlement"); json.put("Occasion", "1234567891"); message = json.toString(); System.out.println("This is the JSON String : " + message); } catch (JSONException ex) { Logger.getLogger(MobilePayAPI.class.getName()).log(Level.SEVERE, null, ex); } RequestBody body = RequestBody.create(mediaType, message); Request request = new Request.Builder().url("https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest") .post(body).addHeader("authorization", "Bearer " + accessToken) .addHeader("content-type", "application/json").build(); try { System.out.println("Request Build Security Credentials : [" + this.encryptInitiatorPassword("cert.cer", "3414") + "]"); System.out.println("Request Build : [" + request.body().toString() + "]"); Response response = client.newCall(request).execute(); JSONObject myObject = null; try { myObject = new JSONObject(response.body().string()); } catch (JSONException ex) { Logger.getLogger(MobilePayAPI.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Payment Request Response : " + myObject.toString()); } catch (IOException ex) { ex.printStackTrace(); } }