Search in sources :

Example 91 with Request

use of com.squareup.okhttp.Request in project NewXmPluginSDK by MiEcosystem.

the class TestCaseActivity method uploadFile.

public Response uploadFile(String url, String filePath) throws IOException {
    Log.d("test", "url:" + url);
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(30, TimeUnit.SECONDS);
    client.setReadTimeout(15, TimeUnit.SECONDS);
    client.setWriteTimeout(30, TimeUnit.SECONDS);
    Request request = new Request.Builder().url(url).put(RequestBody.create(MediaType.parse(""), new File(filePath))).build();
    return client.newCall(request).execute();
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request) File(java.io.File)

Example 92 with Request

use of com.squareup.okhttp.Request 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 93 with Request

use of com.squareup.okhttp.Request in project Android-Universal-Image-Loader by nostra13.

the class OkHttpImageDownloader method getStreamFromNetwork.

@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
    Request request = new Request.Builder().url(imageUri).build();
    ResponseBody responseBody = client.newCall(request).execute().body();
    InputStream inputStream = responseBody.byteStream();
    int contentLength = (int) responseBody.contentLength();
    return new ContentLengthInputStream(inputStream, contentLength);
}
Also used : ContentLengthInputStream(com.nostra13.universalimageloader.core.assist.ContentLengthInputStream) ContentLengthInputStream(com.nostra13.universalimageloader.core.assist.ContentLengthInputStream) InputStream(java.io.InputStream) Request(com.squareup.okhttp.Request) ResponseBody(com.squareup.okhttp.ResponseBody)

Example 94 with Request

use of com.squareup.okhttp.Request in project grpc-java by grpc.

the class OkHttpClientTransport method createHttpProxySocket.

private Socket createHttpProxySocket(InetSocketAddress address, InetSocketAddress proxyAddress, String proxyUsername, String proxyPassword) throws StatusException {
    try {
        Socket sock;
        // The proxy address may not be resolved
        if (proxyAddress.getAddress() != null) {
            sock = socketFactory.createSocket(proxyAddress.getAddress(), proxyAddress.getPort());
        } else {
            sock = socketFactory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort());
        }
        sock.setTcpNoDelay(true);
        Source source = Okio.source(sock);
        BufferedSink sink = Okio.buffer(Okio.sink(sock));
        // Prepare headers and request method line
        Request proxyRequest = createHttpProxyRequest(address, proxyUsername, proxyPassword);
        HttpUrl url = proxyRequest.httpUrl();
        String requestLine = String.format("CONNECT %s:%d HTTP/1.1", url.host(), url.port());
        // Write request to socket
        sink.writeUtf8(requestLine).writeUtf8("\r\n");
        for (int i = 0, size = proxyRequest.headers().size(); i < size; i++) {
            sink.writeUtf8(proxyRequest.headers().name(i)).writeUtf8(": ").writeUtf8(proxyRequest.headers().value(i)).writeUtf8("\r\n");
        }
        sink.writeUtf8("\r\n");
        // Flush buffer (flushes socket and sends request)
        sink.flush();
        // Read status line, check if 2xx was returned
        StatusLine statusLine = StatusLine.parse(readUtf8LineStrictUnbuffered(source));
        // Drain rest of headers
        while (!readUtf8LineStrictUnbuffered(source).equals("")) {
        }
        if (statusLine.code < 200 || statusLine.code >= 300) {
            Buffer body = new Buffer();
            try {
                sock.shutdownOutput();
                source.read(body, 1024);
            } catch (IOException ex) {
                body.writeUtf8("Unable to read body: " + ex.toString());
            }
            try {
                sock.close();
            } catch (IOException ignored) {
            // ignored
            }
            String message = String.format("Response returned from proxy was not successful (expected 2xx, got %d %s). " + "Response body:\n%s", statusLine.code, statusLine.message, body.readUtf8());
            throw Status.UNAVAILABLE.withDescription(message).asException();
        }
        return sock;
    } catch (IOException e) {
        throw Status.UNAVAILABLE.withDescription("Failed trying to connect with proxy").withCause(e).asException();
    }
}
Also used : StatusLine(com.squareup.okhttp.internal.http.StatusLine) Buffer(okio.Buffer) Request(com.squareup.okhttp.Request) BufferedSink(okio.BufferedSink) ByteString(okio.ByteString) IOException(java.io.IOException) SSLSocket(javax.net.ssl.SSLSocket) Socket(java.net.Socket) BufferedSource(okio.BufferedSource) Source(okio.Source) HttpUrl(com.squareup.okhttp.HttpUrl)

Example 95 with Request

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

the class PictureSizeHttpUtility method doGet.

@Override
public <T> T doGet(HttpConfig config, Setting action, Params urlParams, Class<T> responseCls) throws TaskException {
    if (GlobalContext.getInstance() == null || SystemUtils.getNetworkType(GlobalContext.getInstance()) == SystemUtils.NetWorkType.none)
        return null;
    String url = urlParams.getParameter("path");
    PictureSize size = new PictureSize();
    size.setUrl(url);
    Request request = new Request.Builder().url(url).build();
    try {
        Response response = GlobalContext.getOkHttpClient().newCall(request).execute();
        if (!(response.code() == HttpURLConnection.HTTP_OK || response.code() == HttpURLConnection.HTTP_PARTIAL)) {
            throw new TaskException(String.valueOf(TaskException.TaskError.failIOError));
        } else {
            // 图片大小
            String header = response.header("Content-Length");
            int length = Integer.parseInt(header);
            size.setSize(length);
            SinaDB.getDB().insert(null, size);
            Logger.d(TAG, String.format("图片大小 %s", String.valueOf(size.getSize())));
        }
    } catch (Exception e) {
        throw new TaskException(String.valueOf(TaskException.TaskError.failIOError));
    }
    return (T) size;
}
Also used : Response(com.squareup.okhttp.Response) PictureSize(org.aisen.weibo.sina.support.bean.PictureSize) TaskException(org.aisen.android.network.task.TaskException) Request(com.squareup.okhttp.Request) TaskException(org.aisen.android.network.task.TaskException)

Aggregations

Request (com.squareup.okhttp.Request)109 Response (com.squareup.okhttp.Response)74 IOException (java.io.IOException)61 OkHttpClient (com.squareup.okhttp.OkHttpClient)38 RequestBody (com.squareup.okhttp.RequestBody)31 FormEncodingBuilder (com.squareup.okhttp.FormEncodingBuilder)19 UnsupportedEncodingException (java.io.UnsupportedEncodingException)12 File (java.io.File)11 Callback (com.squareup.okhttp.Callback)10 InputStream (java.io.InputStream)7 Buffer (okio.Buffer)7 HttpUrl (com.squareup.okhttp.HttpUrl)5 MediaType (com.squareup.okhttp.MediaType)5 ResponseBody (com.squareup.okhttp.ResponseBody)5 SocketTimeoutException (java.net.SocketTimeoutException)5 Call (com.squareup.okhttp.Call)4 FileOutputStream (java.io.FileOutputStream)4 Activity (android.app.Activity)3 Intent (android.content.Intent)3 Uri (android.net.Uri)3