List of usage examples for com.squareup.okhttp ResponseBody bytes
public final byte[] bytes() throws IOException
From source file:BenchMarkTest.java
License:Open Source License
void doOkHttpRequest() { ++okhttp_task_cnt;// w w w .j av a2 s . c o m try { OkHttpClient client = new OkHttpClient(); Main.HelloRequest req = new Main.HelloRequest(); req.user = "okhttp"; req.text = Integer.toString((int) okhttp_task_cnt); //Benchmark 64KB/128KB /*req.dumpContent = new byte[64*1024]; Random rand = new Random(); rand.nextBytes(req.dumpContent);*/ final byte[] flatArray = new byte[req.getSerializedSize()]; final CodedOutputByteBufferNano output = CodedOutputByteBufferNano.newInstance(flatArray); req.writeTo(output); RequestBody reqBody = RequestBody.create(MediaType.parse("application/octet-stream"), flatArray); //normal request Request request = new Request.Builder().url("http://118.89.24.72:8080/mars/hello2") .addHeader("Cache-Control", "no-cache").addHeader("Content-Type", "application/octet-stream") .addHeader("Connection", "close").addHeader("Accept", "*/*").post(reqBody).build(); okhttp_task_time = System.currentTimeMillis(); // Execute the request and retrieve the response. Response response = client.newCall(request).execute(); ResponseBody body = response.body(); Main.HelloResponse helloResp = Main.HelloResponse.parseFrom(body.bytes()); body.close(); long curr = System.currentTimeMillis(); okhttp_suc_time += curr - okhttp_task_time; ++okhttp_task_suc; //Log.i(TAG, "http type:" + type + ", suc cost:" + (curr - okhttp_task_time) + ", count:" + okhttp_task_cnt + ", suc count:" + okhttp_task_suc + ", ctn:" + helloResp.errmsg); } catch (Exception e) { Log.e(TAG, "http fail cost:" + (System.currentTimeMillis() - okhttp_task_time) + ", count:" + okhttp_task_cnt); } }
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);/*from ww w . j av 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:com.magnet.max.android.rest.marshalling.MagnetGsonConverter.java
License:Apache License
@Override public T fromBody(ResponseBody responseBody) throws IOException { if (GsonDecorator.getInstance().isVoidType(typeToken.getType())) { return null; }// www. j ava2 s. com if (typeToken.getRawType().equals(ResponseBody.class)) { return (T) responseBody; } if (GsonDecorator.getInstance().isByteArray(typeToken)) { return (T) responseBody.bytes(); } //Charset charset = UTF_8; //if (responseBody.contentType() != null) { // charset = responseBody.contentType().charset(charset); //} if (GsonDecorator.getInstance().isSimpleType(typeToken)) { return (T) GsonDecorator.getInstance().unmarshalSimpleType(responseBody.string(), typeToken.getType()); } else { Reader in = responseBody.charStream(); try { return (T) GsonDecorator.getInstance().fromJson(responseBody.charStream(), typeToken); //typeAdapter.fromJson(in); } catch (Exception e) { Log.e(TAG, "Error in fromBody \n" + e.getMessage()); throw e; } finally { try { in.close(); } catch (IOException ignored) { } } } }
From source file:org.dataconservancy.cos.osf.client.retrofit.PaginatedResponseBodyConverter.java
License:Apache License
/** * {@inheritDoc}// w ww. j a v a2 s . co m * <p> * Implementation note: if {@code isCollection} is {@code true}, the collection returned by the ResourceConverter * will be adapted to a {@code PaginatedList} and returned. * </p> * @param responseBody the response returned from the API * @return a potentially paginated response * @throws IOException {@inheritDoc} */ @Override public T convert(final ResponseBody responseBody) throws IOException { if (isCollection) { return (T) new PaginatedListAdapter<>(okHttp, resourceConverter, clazz, resourceConverter.readObjectCollection(responseBody.bytes(), clazz)); } else { return resourceConverter.readObject(responseBody.bytes(), clazz); } }
From source file:org.dkf.jed2k.util.http.OKHTTPClient.java
License:Open Source License
@Override public byte[] getBytes(String url, int timeout, String userAgent, String referrer, String cookies) { byte[] result = null; final OkHttpClient okHttpClient = newOkHttpClient(); final Request.Builder builder = prepareRequestBuilder(okHttpClient, url, timeout, userAgent, referrer, cookies);/*from www . j ava 2 s. c o m*/ ResponseBody responseBody = null; try { responseBody = getSyncResponse(okHttpClient, builder).body(); result = responseBody.bytes(); } catch (Throwable e) { LOG.error("Error getting bytes from http body response: " + e.getMessage(), e); } finally { if (responseBody != null) { closeQuietly(responseBody); } } return result; }