Example usage for com.squareup.okhttp OkHttpClient newCall

List of usage examples for com.squareup.okhttp OkHttpClient newCall

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient newCall.

Prototype

public Call newCall(Request request) 

Source Link

Document

Prepares the request to be executed at some point in the future.

Usage

From source file:com.ydh.gva.util.net.volley.toolbox.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();
    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();
    okHttpRequestBuilder.addHeader("clientos", "101");
    okHttpRequestBuilder.addHeader("osversion", SystemVal.sdk + "");
    okHttpRequestBuilder.addHeader("clientphone", SystemVal.model + "");
    okHttpRequestBuilder.addHeader("weiLeversion", SystemVal.versionCode + "");

    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }//from ww w  . ja v  a 2 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:de.ebf.GetTranslationsOneSkyAppMojo.java

License:Apache License

private void getTranslations() throws MojoExecutionException {
    try {//from  w  w  w. j a  v a2 s.  c om
        for (String sourceFileName : sourceFileNames) {
            for (String locale : locales) {
                System.out
                        .println(String.format("Downloading %1s translations for %2s", locale, sourceFileName));

                OkHttpClient okHttpClient = new OkHttpClient();
                final String url = String.format(
                        API_ENDPOINT + "projects/%1$s/translations?locale=%2$s&source_file_name=%3$s&%4$s",
                        projectId, locale, sourceFileName, getAuthParams());
                final Request request = new Request.Builder().get().url(url).build();
                final Response response = okHttpClient.newCall(request).execute();

                if (response.code() == 200) {
                    if (!outputDir.exists()) {
                        outputDir.mkdirs();
                    }
                    //even though the OneSkyApp API documentation states that the file name should be sourceFileName_locale.sourceFileNameExtension, it is just locale.sourceFileNameExtension)
                    //https://github.com/onesky/api-documentation-platform/blob/master/resources/translation.md

                    String targetFileName = sourceFileName + "_" + locale;
                    int index = sourceFileName.lastIndexOf(".");
                    if (index > 0) {
                        targetFileName = sourceFileName.substring(0, index) + "_" + locale + "."
                                + sourceFileName.substring(index + 1);
                    }
                    File outputFile = new File(outputDir, targetFileName);
                    outputFile.createNewFile();
                    final InputStream inputStream = response.body().byteStream();
                    FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
                    IOUtils.copy(inputStream, fileOutputStream);
                    System.out.println(String.format("Successfully downloaded %1s translation for %2s to %3s",
                            locale, sourceFileName, outputFile.getName()));
                } else {
                    throw new MojoExecutionException(String.format("OneSkyApp API returned %1$s: %2s",
                            response.code(), response.message()));
                }
            }
        }
    } catch (IOException | MojoExecutionException ex) {
        if (failOnError == null || failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            System.out.println("Caught exception: " + ex.getMessage());
        }
    }
}

From source file:de.ebf.UploadFileOneSkyAppMojo.java

License:Apache License

private void uploadFiles() throws MojoExecutionException {
    try {//w  w w .  ja v  a 2 s  .  com
        for (File file : files) {
            System.out.println(String.format("Uploading %1$s", file.getName()));
            OkHttpClient okHttpClient = new OkHttpClient();
            final String url = String.format(
                    API_ENDPOINT + "projects/%1$s/files?file_format=%2$s&locale=%3$s&%4$s", projectId,
                    fileFormat, locale, getAuthParams());

            RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                    .addPart(
                            Headers.of("Content-Disposition",
                                    "form-data; name=\"file\"; filename=\"" + file.getName() + "\""),
                            RequestBody.create(MediaType.parse("text/plain"), file))
                    .build();

            final Request request = new Request.Builder().post(requestBody).url(url).build();
            final Response response = okHttpClient.newCall(request).execute();

            if (response.code() == 201) {
                System.out.println(String.format("Successfully uploaded %1$s", file.getName()));
            } else {
                throw new MojoExecutionException(String.format("OneSkyApp API returned %1$s: %2s, %3$s",
                        response.code(), response.message(), response.body().string()));
            }
        }
    } catch (IOException | MojoExecutionException ex) {
        if (failOnError == null || failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            System.out.println("Caught exception: " + ex.getMessage());
        }
    }
}

From source file:de.l3s.boilerpipe.sax.HTMLFetcher.java

License:Apache License

public static HTMLDocument fetchOk(final String url) throws IOException {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();

    Response response = client.newCall(request).execute();

    String data = response.body().string();
    Charset cs = response.body().contentType().charset();
    return new HTMLDocument(data, cs);
}

From source file:de.schildbach.wallet.data.DynamicFeeLoader.java

License:Open Source License

private static void fetchDynamicFees(final HttpUrl url, final File tempFile, final File targetFile,
        final String userAgent) {
    final Stopwatch watch = Stopwatch.createStarted();

    final Request.Builder request = new Request.Builder();
    request.url(url);/* w  ww  .j a v  a 2  s  .  com*/
    request.header("User-Agent", userAgent);
    if (targetFile.exists())
        request.header("If-Modified-Since", HttpDate.format(new Date(targetFile.lastModified())));

    final OkHttpClient httpClient = Constants.HTTP_CLIENT.clone();
    httpClient.setConnectTimeout(5, TimeUnit.SECONDS);
    httpClient.setWriteTimeout(5, TimeUnit.SECONDS);
    httpClient.setReadTimeout(5, TimeUnit.SECONDS);
    final Call call = httpClient.newCall(request.build());
    try {
        final Response response = call.execute();
        final int status = response.code();
        if (status == HttpURLConnection.HTTP_NOT_MODIFIED) {
            log.info("Dynamic fees not modified at {}, took {}", url, watch);
        } else if (status == HttpURLConnection.HTTP_OK) {
            final ResponseBody body = response.body();
            final FileOutputStream os = new FileOutputStream(tempFile);
            Io.copy(body.byteStream(), os);
            os.close();
            final Date lastModified = response.headers().getDate("Last-Modified");
            if (lastModified != null)
                tempFile.setLastModified(lastModified.getTime());
            body.close();
            if (!tempFile.renameTo(targetFile))
                throw new IllegalStateException("Cannot rename " + tempFile + " to " + targetFile);
            watch.stop();
            log.info("Dynamic fees fetched from {}, took {}", url, watch);
        } else {
            log.warn("HTTP status {} when fetching dynamic fees from {}", response.code(), url);
        }
    } catch (final Exception x) {
        log.warn("Problem when fetching dynamic fees rates from " + url, x);
    }
}

From source file:info.curtbinder.notificationmanager.CommTask.java

License:Open Source License

@Override
public void run() {
    try {/*from  w ww .j a v a 2  s  .c  o m*/
        URL url = new URL(host.toString());
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        XMLNotificationHandler xml = new XMLNotificationHandler();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        XMLReader xr = spf.newSAXParser().getXMLReader();
        xr.setContentHandler(xml);
        String r = response.body().string();
        Intent i = new Intent();
        if (r.equals("Done")) {
            // we got a positive response from our update
            i.setAction(MessageCommands.SERVER_RESPONSE);
            String msg;
            int p1Id;
            String fmt = ctx.getString(R.string.success_msg);
            switch (host.getType()) {
            default:
            case Host.ADD:
                p1Id = R.string.added;
                break;
            case Host.UPDATE:
                p1Id = R.string.updated;
                break;
            case Host.DELETE:
                p1Id = R.string.deleted;
                break;
            }
            msg = String.format(fmt, ctx.getString(p1Id), host.getAlertName());
            i.putExtra(MessageCommands.MSG_RESPONSE, msg);
        } else {
            xr.parse(new InputSource(new StringReader(r)));
            i.setAction(MessageCommands.UPDATE_DISPLAY_ALERTS);
            i.putParcelableArrayListExtra("ALERTS", (ArrayList) xml.getAlerts());
        }
        response.body().close();
        // send message to main thread with the data
        ctx.sendBroadcast(i);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:info.curtbinder.reefangel.service.ControllerTask.java

License:Creative Commons License

public void run() {
    // Communicate with controller

    // clear out the error code on run
    rapp.clearErrorCode();//from w ww  . j  a v  a2 s . c om
    Response response = null;
    boolean fInterrupted = false;
    broadcastUpdateStatus(R.string.statusStart);
    try {
        URL url = new URL(host.toString());
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(host.getConnectTimeout(), TimeUnit.MILLISECONDS);
        client.setReadTimeout(host.getReadTimeout(), TimeUnit.MILLISECONDS);
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (host.isDeviceAuthenticationEnabled()) {
            String creds = Credentials.basic(host.getWifiUsername(), host.getWifiPassword());
            builder.header("Authorization", creds);
        }
        Request req = builder.build();
        broadcastUpdateStatus(R.string.statusConnect);
        response = client.newCall(req).execute();

        if (!response.isSuccessful())
            throw new IOException("Unexpected code " + response);

        if (Thread.interrupted())
            throw new InterruptedException();

    } catch (MalformedURLException e) {
        rapp.error(1, e, "MalformedURLException");
    } catch (SocketTimeoutException e) {
        rapp.error(5, e, "SocketTimeoutException");
    } catch (ConnectException e) {
        rapp.error(3, e, "ConnectException");
    } catch (UnknownHostException e) {
        String msg = "Unknown Host: " + host.toString();
        UnknownHostException ue = new UnknownHostException(msg);
        rapp.error(4, ue, "UnknownHostException");
    } catch (EOFException e) {
        EOFException eof = new EOFException(rapp.getString(R.string.errorAuthentication));
        rapp.error(3, eof, "EOFException");
    } catch (IOException e) {
        rapp.error(3, e, "IOException");
    } catch (InterruptedException e) {
        fInterrupted = true;
    }

    processResponse(response, fInterrupted);
}

From source file:info.rmapproject.cos.osf.client.service.OsfClientService.java

License:Apache License

/**
 * Instantiates a new osf client service.
 *///from  w  ww.ja  v  a 2 s.  c o m
public OsfClientService() {
    try {
        // Create object mapper
        ObjectMapper objectMapper = new ObjectMapper();
        OkHttpClient client = new OkHttpClient();

        ResourceConverter converter = new ResourceConverter(objectMapper, LightNode.class,
                LightRegistration.class, Registration.class, Identifier.class, Contributor.class, User.class,
                LightUser.class, Institution.class, Node.class);
        converter.setGlobalResolver(relUrl -> {
            System.err.println("Resolving " + relUrl);
            com.squareup.okhttp.Call req = client.newCall(new Request.Builder().url(relUrl).build());
            try {
                byte[] bytes = req.execute().body().bytes();
                return bytes;
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        });

        RetrofitOsfServiceFactory factory = new RetrofitOsfServiceFactory("classpath*:/osf-config.json");
        osfService = factory.getOsfService(OsfService.class);

    } catch (Exception e) {
        throw new RuntimeException("Could not start OSF Service", e);
    }
}

From source file:inforuh.eventfinder.sync.SyncAdapter.java

License:Open Source License

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {//from  ww  w .j a  va2  s .c  o  m
    Log.d(LOG_TAG, "Getting event data...");
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(Config.URL).build();

    client.newCall(request).enqueue(this);
}

From source file:io.apptik.comm.jus.okhttp.OkHttpStack.java

License:Apache License

@Override
public NetworkResponse performRequest(Request<?> request, Headers additionalHeaders,
        ByteArrayPool byteArrayPool) throws IOException {

    //clone to be able to set timeouts per call
    OkHttpClient client = this.client.clone();
    client.setConnectTimeout(request.getRetryPolicy().getCurrentConnectTimeout(), TimeUnit.MILLISECONDS);
    client.setReadTimeout(request.getRetryPolicy().getCurrentReadTimeout(), TimeUnit.MILLISECONDS);
    com.squareup.okhttp.Request okRequest = new com.squareup.okhttp.Request.Builder()
            .url(request.getUrlString()).headers(JusOk.okHeaders(request.getHeaders(), additionalHeaders))
            .tag(request.getTag()).method(request.getMethod(), JusOk.okBody(request.getNetworkRequest()))
            .build();/*from   www .  j av  a 2  s. co  m*/

    long requestStart = System.nanoTime();

    Response response = client.newCall(okRequest).execute();

    byte[] data = null;
    if (NetworkDispatcher.hasResponseBody(request.getMethod(), response.code())) {
        data = getContentBytes(response.body().source(), byteArrayPool, (int) response.body().contentLength());
    } else {
        // Add 0 byte response as a way of honestly representing a
        // no-content request.
        data = new byte[0];
    }
    return new NetworkResponse.Builder().setHeaders(JusOk.jusHeaders(response.headers()))
            .setStatusCode(response.code()).setBody(data).setNetworkTimeNs(System.nanoTime() - requestStart)
            .build();
}