Search in sources :

Example 26 with RequestBody

use of com.squareup.okhttp.RequestBody in project Notes by lguipeng.

the class TAndroidTransport method flush.

@Override
public void flush() throws TTransportException {
    Util.closeQuietly(mResponseBody);
    mResponseBody = null;
    RequestBody requestBody = new RequestBody() {

        @Override
        public MediaType contentType() {
            if (mHeaders != null && mHeaders.containsKey("Content-Type")) {
                return MediaType.parse(mHeaders.get("Content-Type"));
            } else {
                return MEDIA_TYPE_THRIFT;
            }
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            copy(mByteStore.getInputStream(), sink.outputStream());
        }
    };
    try {
        Request.Builder builder = new Request.Builder().url(mUrl).post(requestBody);
        if (mHeaders != null) {
            for (String name : mHeaders.keySet()) {
                builder.header(name, mHeaders.get(name));
            }
        }
        Response response = mHttpClient.newCall(builder.build()).execute();
        if (response.code() != 200) {
            throw new TTransportException("HTTP Response code: " + response.code() + ", message " + response.message());
        }
        mResponseBody = response.body().byteStream();
    } catch (Exception e) {
        throw new TTransportException(e);
    } finally {
        try {
            mByteStore.reset();
        } catch (IOException ignored) {
        }
    }
}
Also used : Response(com.squareup.okhttp.Response) Request(com.squareup.okhttp.Request) TTransportException(com.evernote.thrift.transport.TTransportException) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) IOException(java.io.IOException) TTransportException(com.evernote.thrift.transport.TTransportException) RequestBody(com.squareup.okhttp.RequestBody)

Example 27 with RequestBody

use of com.squareup.okhttp.RequestBody in project rskj by rsksmart.

the class Web3WebSocketServerTest method smokeTest.

private void smokeTest(byte[] msg) throws Exception {
    Web3 web3Mock = mock(Web3.class);
    String mockResult = "output";
    when(web3Mock.web3_sha3(anyString())).thenReturn(mockResult);
    int randomPort = 9998;
    TestSystemProperties testSystemProperties = new TestSystemProperties();
    List<ModuleDescription> filteredModules = Collections.singletonList(new ModuleDescription("web3", "1.0", true, Collections.emptyList(), Collections.emptyList()));
    RskWebSocketJsonRpcHandler handler = new RskWebSocketJsonRpcHandler(null);
    JsonRpcWeb3ServerHandler serverHandler = new JsonRpcWeb3ServerHandler(web3Mock, filteredModules);
    int serverWriteTimeoutSeconds = testSystemProperties.rpcWebSocketServerWriteTimeoutSeconds();
    int maxFrameSize = testSystemProperties.rpcWebSocketMaxFrameSize();
    int maxAggregatedFrameSize = testSystemProperties.rpcWebSocketMaxAggregatedFrameSize();
    assertEquals(DEFAULT_WRITE_TIMEOUT_SECONDS, serverWriteTimeoutSeconds);
    assertEquals(DEFAULT_MAX_FRAME_SIZE, maxFrameSize);
    assertEquals(DEFAULT_MAX_AGGREGATED_FRAME_SIZE, maxAggregatedFrameSize);
    Web3WebSocketServer websocketServer = new Web3WebSocketServer(InetAddress.getLoopbackAddress(), randomPort, handler, serverHandler, serverWriteTimeoutSeconds, maxFrameSize, maxAggregatedFrameSize);
    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, msg);
                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());
    }
}
Also used : WebSocketListener(com.squareup.okhttp.ws.WebSocketListener) OkHttpClient(com.squareup.okhttp.OkHttpClient) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) WebSocketCall(com.squareup.okhttp.ws.WebSocketCall) Web3(org.ethereum.rpc.Web3) RequestBody(com.squareup.okhttp.RequestBody) Buffer(okio.Buffer) Request(com.squareup.okhttp.Request) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) WebSocket(com.squareup.okhttp.ws.WebSocket) ResponseBody(com.squareup.okhttp.ResponseBody) Response(com.squareup.okhttp.Response) ModuleDescription(co.rsk.rpc.ModuleDescription) TestSystemProperties(co.rsk.config.TestSystemProperties)

Example 28 with RequestBody

use of com.squareup.okhttp.RequestBody in project AisenWeiBo by wangdan.

the class DefHttpUtility method doPostFiles.

@Override
public <T> T doPostFiles(HttpConfig config, Setting action, Params urlParams, Params bodyParams, MultipartFile[] files, Class<T> responseCls) throws TaskException {
    String method = "doPostFiles";
    Request.Builder builder = createRequestBuilder(config, action, urlParams, method);
    MultipartBuilder multipartBuilder = new MultipartBuilder();
    multipartBuilder.type(MultipartBuilder.FORM);
    // 处理Body参数
    if (bodyParams != null && bodyParams.getKeys().size() > 0) {
        for (String key : bodyParams.getKeys()) {
            String value = bodyParams.getParameter(key);
            multipartBuilder.addFormDataPart(key, value);
            Logger.d(getTag(action, method), "BodyParam[%s, %s]", key, value);
        }
    }
    // 处理文件数据
    if (files != null && files.length > 0) {
        for (MultipartFile file : files) {
            // 普通字节流
            if (file.getBytes() != null) {
                multipartBuilder.addFormDataPart(file.getKey(), file.getKey(), createRequestBody(file));
                Logger.d(getTag(action, method), "Multipart bytes, length = " + file.getBytes().length);
            } else // 文件
            if (file.getFile() != null) {
                multipartBuilder.addFormDataPart(file.getKey(), file.getFile().getName(), createRequestBody(file));
                Logger.d(getTag(action, method), "Multipart file, name = %s, path = %s", file.getFile().getName(), file.getFile().getAbsolutePath());
            }
        }
    }
    RequestBody requestBody = multipartBuilder.build();
    builder.post(requestBody);
    return executeRequest(builder.build(), responseCls, action, method);
}
Also used : Request(com.squareup.okhttp.Request) MultipartBuilder(com.squareup.okhttp.MultipartBuilder) RequestBody(com.squareup.okhttp.RequestBody)

Example 29 with RequestBody

use of com.squareup.okhttp.RequestBody in project pictureapp by EyeSeeTea.

the class PushClient method pushData.

/**
 * Pushes data to DHIS Server
 */
private JSONObject pushData(JSONObject data) throws ApiCallException {
    Response response = null;
    final String DHIS_URL = getDhisURL();
    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();
    // connect timeout
    client.setConnectTimeout(30, TimeUnit.SECONDS);
    // socket timeout
    client.setReadTimeout(30, TimeUnit.SECONDS);
    // write timeout
    client.setWriteTimeout(30, TimeUnit.SECONDS);
    // Cancel retry on failure
    client.setRetryOnConnectionFailure(false);
    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);
    RequestBody body = RequestBody.create(JSON, data.toString());
    Request request = new Request.Builder().header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL).post(body).build();
    try {
        response = client.newCall(request).execute();
    } catch (IOException e) {
        throw new ApiCallException(e);
    }
    return ServerApiUtils.getApiResponseAsJSONObject(response);
}
Also used : Response(com.squareup.okhttp.Response) OkHttpClient(com.squareup.okhttp.OkHttpClient) ApiCallException(org.eyeseetea.malariacare.domain.exception.ApiCallException) Request(com.squareup.okhttp.Request) IOException(java.io.IOException) RequestBody(com.squareup.okhttp.RequestBody)

Example 30 with RequestBody

use of com.squareup.okhttp.RequestBody in project pictureapp by EyeSeeTea.

the class BasicAuthenticator method executeCall.

/**
 * Call to DHIS Server
 */
static Response executeCall(JSONObject data, String url, String method) throws ApiCallException {
    final String DHIS_URL = url;
    Log.d(method, DHIS_URL);
    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();
    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);
    Request.Builder builder = new Request.Builder().header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL);
    switch(method) {
        case "POST":
            RequestBody postBody = RequestBody.create(JSON, data.toString());
            builder.post(postBody);
            break;
        case "PUT":
            RequestBody putBody = RequestBody.create(JSON, data.toString());
            builder.put(putBody);
            break;
        case "PATCH":
            RequestBody patchBody = RequestBody.create(JSON, data.toString());
            builder.patch(patchBody);
            break;
        case "GET":
            builder.get();
            break;
    }
    Request request = builder.build();
    Response response = null;
    try {
        response = client.newCall(request).execute();
    } catch (IOException ex) {
        throw new ApiCallException(ex);
    }
    return response;
}
Also used : Response(com.squareup.okhttp.Response) OkHttpClient(com.squareup.okhttp.OkHttpClient) ApiCallException(org.eyeseetea.malariacare.domain.exception.ApiCallException) Request(com.squareup.okhttp.Request) IOException(java.io.IOException) ConfigJsonIOException(org.eyeseetea.malariacare.domain.exception.ConfigJsonIOException) RequestBody(com.squareup.okhttp.RequestBody)

Aggregations

RequestBody (com.squareup.okhttp.RequestBody)39 Request (com.squareup.okhttp.Request)33 Response (com.squareup.okhttp.Response)24 IOException (java.io.IOException)19 OkHttpClient (com.squareup.okhttp.OkHttpClient)14 FormEncodingBuilder (com.squareup.okhttp.FormEncodingBuilder)12 BufferedSink (okio.BufferedSink)7 MultipartBuilder (com.squareup.okhttp.MultipartBuilder)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 Call (com.squareup.okhttp.Call)3 Buffer (okio.Buffer)3 Activity (android.app.Activity)2 PowerManager (android.os.PowerManager)2 AppCompatActivity (android.support.v7.app.AppCompatActivity)2 EditText (android.widget.EditText)2 BaseAppCompatActivity (com.eveningoutpost.dexdrip.BaseAppCompatActivity)2 MediaType (com.squareup.okhttp.MediaType)2 CookieManager (java.net.CookieManager)2 GzipSink (okio.GzipSink)2 ApiCallException (org.eyeseetea.malariacare.domain.exception.ApiCallException)2