Example usage for com.squareup.okhttp Call execute

List of usage examples for com.squareup.okhttp Call execute

Introduction

In this page you can find the example usage for com.squareup.okhttp Call execute.

Prototype

public Response execute() throws IOException 

Source Link

Document

Invokes the request immediately, and blocks until the response can be processed or is in error.

Usage

From source file:com.danilov.supermanga.core.repository.HentaichanEngine.java

License:Open Source License

@Override
public List<Manga> queryRepository(final String query, final List<Filter.FilterValue> filterValues)
        throws RepositoryException {
    final String response = doWithLoginAttempt(() -> {
        final Call call = httpClient.newCall(new Request.Builder()
                .url(baseUri + "?do=search&subaction=search&story=" + URLEncoder.encode(query, "UTF-8")).get()
                .build());//from  w ww. ja  va2  s .c o m
        final Response rsp;
        try {
            rsp = call.execute();
        } catch (IOException e) {
            throw new RepositoryException("Failed to load: " + e.getMessage());
        }
        return rsp;
    });
    final Document document;
    document = Utils.toDocument(response);
    final List<Manga> mangas = parseSearchResponse(document);
    return mangas;
}

From source file:com.danilov.supermanga.core.repository.HentaichanEngine.java

License:Open Source License

@Override
public boolean queryForMangaDescription(final Manga manga) throws RepositoryException {
    final String response = doWithLoginAttempt(() -> {
        final Call call = httpClient.newCall(new Request.Builder().url(manga.getUri()).get().build());
        final Response rsp;
        try {/* www. j a va 2 s.c o  m*/
            rsp = call.execute();
        } catch (IOException e) {
            throw new RepositoryException("Failed to load: " + e.getMessage());
        }
        return rsp;
    });

    final Document document;
    document = Utils.toDocument(response);

    final boolean description = parseMangaDescriptionResponse(manga, document);
    final boolean chapters = queryForChapters(manga);

    return description && chapters;
}

From source file:com.danilov.supermanga.core.repository.HentaichanEngine.java

License:Open Source License

private String loadPage(final String uri) throws RepositoryException {
    return doWithLoginAttempt(() -> {
        final Call call = httpClient.newCall(new Request.Builder().url(uri).get().build());
        final Response rsp;
        try {//w  ww.  ja  v  a  2s .com
            rsp = call.execute();
        } catch (IOException e) {
            throw new RepositoryException("Failed to load: " + e.getMessage());
        }
        return rsp;
    });
}

From source file:com.danilov.supermanga.core.repository.HentaichanEngine.java

License:Open Source License

@Override
public List<String> getChapterImages(final MangaChapter chapter) throws RepositoryException {
    String uri = baseUri + chapter.getUri();
    final String response = doWithLoginAttempt(() -> {
        final Call call = httpClient.newCall(new Request.Builder().url(uri).get().build());
        final Response rsp;
        try {/*from   w w w  .j a  va2  s .com*/
            rsp = call.execute();
        } catch (IOException e) {
            throw new RepositoryException("Failed to load: " + e.getMessage());
        }
        return rsp;
    });

    final InputStream stream;
    try {
        stream = new ByteArrayInputStream(response.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new RepositoryException("Failed to load: " + e.getMessage());
    }

    try {
        byte[] bytes = new byte[1024];
        final LinesSearchInputStream inputStream = new LinesSearchInputStream(stream, "\"fullimg\":[", "]");
        int status = LinesSearchInputStream.SEARCHING;
        while (status == LinesSearchInputStream.SEARCHING) {
            status = inputStream.read(bytes);
        }
        bytes = inputStream.getResult();
        String str = IoUtils.convertBytesToString(bytes);
        return extractUrls(str);
    } catch (Exception e) {

    }
    return null;
}

From source file:com.datastore_android_sdk.okhttp.OkHttpStack.java

License:Open Source License

@Override
public URLHttpResponse performRequest(Request<?> request, ArrayList<HttpParamsEntry> additionalHeaders)
        throws IOException {
    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    for (final HttpParamsEntry entry : request.getHeaders()) {
        okHttpRequestBuilder.addHeader(entry.k, entry.v);
    }//from w ww .ja v  a2s.c om
    for (final HttpParamsEntry entry : additionalHeaders) {
        okHttpRequestBuilder.addHeader(entry.k, entry.v);
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);
    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    return responseFromConnection(okHttpResponse);
}

From source file:com.facebook.buck.slb.ClientSideSlbTest.java

License:Apache License

@Test
@SuppressWarnings("unchecked")
public void testAllServersArePinged() throws IOException {
    Capture<Runnable> capture = EasyMock.newCapture();
    EasyMock.expect(mockScheduler.scheduleWithFixedDelay(EasyMock.capture(capture), EasyMock.anyLong(),
            EasyMock.anyLong(), EasyMock.anyObject(TimeUnit.class))).andReturn(mockFuture).once();
    Call mockCall = EasyMock.createMock(Call.class);
    EasyMock.expect(mockCall.execute()).andReturn(null).times(SERVERS.size());
    EasyMock.expect(mockClient.newCall(EasyMock.anyObject(Request.class))).andReturn(mockCall)
            .times(SERVERS.size());/* ww  w  .  j  ava  2 s  . com*/
    EasyMock.replay(mockClient, mockCall, mockScheduler);

    try (ClientSideSlb slb = new ClientSideSlb(config)) {
        Runnable healthCheckLoop = capture.getValue();
        healthCheckLoop.run();
    }
}

From source file:com.facebook.buck.slb.LoadBalancedService.java

License:Apache License

@Override
public Response makeRequest(String path, Request.Builder requestBuilder) throws IOException {
    URI server = slb.getBestServer();
    LoadBalancedServiceEventData.Builder data = LoadBalancedServiceEventData.builder().setServer(server);
    requestBuilder.url(SingleUriService.getFullUrl(server, path));
    Request request = requestBuilder.build();
    if (request.body() != null && request.body().contentLength() != -1) {
        data.setRequestSizeBytes(request.body().contentLength());
    }//  w w  w. j  ava 2 s. c  o m
    Call call = client.newCall(request);
    try {
        Response response = call.execute();
        if (response.body() != null && response.body().contentLength() != -1) {
            data.setResponseSizeBytes(response.body().contentLength());
        }
        slb.reportRequestSuccess(server);
        return response;
    } catch (IOException e) {
        data.setException(e);
        slb.reportRequestException(server);
        throw new IOException(e);
    } finally {
        eventBus.post(new LoadBalancedServiceEvent(data.build()));
    }
}

From source file:com.facebook.buck.slb.SingleUriServiceTest.java

License:Apache License

@Test
public void testClientIsCalledWithFullUrl() throws IOException, InterruptedException {
    OkHttpClient mockClient = EasyMock.createMock(OkHttpClient.class);
    String path = "my/super/path";
    Request.Builder request = new Request.Builder().url(SERVER + path).get();
    Call mockCall = EasyMock.createMock(Call.class);
    EasyMock.expect(mockClient.newCall(EasyMock.anyObject(Request.class))).andReturn(mockCall);
    Response response = new Response.Builder().message("my super response").request(request.build())
            .protocol(Protocol.HTTP_1_1).code(200).build();
    EasyMock.expect(mockCall.execute()).andReturn(response);
    EasyMock.replay(mockCall, mockClient);
    try (SingleUriService service = new SingleUriService(SERVER, mockClient)) {
        service.makeRequest(path, request);
    }//from w ww .  j  av  a  2 s .  c o m
}

From source file:com.gezhii.fitgroup.network.OkHttpStack.java

License:Open Source License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    //int timeoutMs = request.getTimeoutMs();
    int timeoutMs = 30000;
    Log.i("timeoutMs", timeoutMs);
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/* w w  w  .j  a  v  a2 s. c  o m*/
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:com.hippo.network.DownloadClient.java

License:Apache License

public static boolean execute(DownloadRequest request) {
    OnDownloadListener listener = request.mListener;
    OkHttpClient okHttpClient = request.mOkHttpClient;

    UniFile uniFile = null;/*from   www. java  2 s .co m*/
    OutputStreamPipe osPipe = null;
    try {
        Call call = okHttpClient.newCall(new GoodRequestBuilder(request.mUrl).build());
        request.mCall = call;

        // Listener
        if (listener != null) {
            listener.onStartDownloading();
        }

        Response response = call.execute();
        ResponseBody body = response.body();

        // Check response code
        int responseCode = response.code();
        if (responseCode >= 400) {
            throw new ResponseCodeException(responseCode);
        }

        osPipe = request.mOSPipe;
        if (osPipe == null) {
            String extension;
            String name;

            String dispositionFilename = getFilenameFromContentDisposition(
                    response.header("Content-Disposition"));
            if (dispositionFilename != null) {
                name = FileUtils.getNameFromFilename(dispositionFilename);
                extension = FileUtils.getExtensionFromFilename(dispositionFilename);
            } else {
                name = Utilities.getNameFromUrl(request.mUrl);
                extension = Utilities.getExtensionFromMimeType(response.header("Content-Type"));
                if (extension == null) {
                    extension = MimeTypeMap.getFileExtensionFromUrl(request.mUrl);
                }
            }

            String filename;
            if (listener != null) {
                filename = listener.onFixname(name, extension, request.mFilename);
            } else {
                filename = request.mFilename;
            }
            request.mFilename = filename;

            // Use Temp filename
            uniFile = request.mDir.createFile(FileUtils.ensureFilename(filename + ".download"));
            if (uniFile == null) {
                // Listener
                if (listener != null) {
                    listener.onFailed(new IOException("Can't create file " + filename));
                }
                return false;
            }
            osPipe = new UniFileOutputStreamPipe(uniFile);
        }
        osPipe.obtain();

        long contentLength = body.contentLength();

        // Listener
        if (listener != null) {
            listener.onConnect(contentLength);
        }

        long receivedSize = transferData(body.byteStream(), osPipe.open(), listener);

        if (contentLength > 0 && contentLength != receivedSize) {
            throw new IOException(
                    "contentLength is " + contentLength + ", but receivedSize is " + receivedSize);
        }

        // Rename
        if (uniFile != null && request.mFilename != null) {
            uniFile.renameTo(request.mFilename);
        }

        // Listener
        if (listener != null) {
            listener.onSucceed();
        }
        return true;
    } catch (Exception e) {
        // remove download failed file
        if (uniFile != null) {
            uniFile.delete();
        }

        if (listener != null) {
            listener.onFailed(e);
        }
        return false;
    } finally {
        if (osPipe != null) {
            osPipe.close();
            osPipe.release();
        }
    }
}