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:org.mythtv.services.api.ServerVersionQuery.java

License:Apache License

private static boolean isServerReachable(String baseUrl, OkHttpClient client) throws IOException {
    Request request = new Request.Builder().url(baseUrl)
            .addHeader("User-Agent", "MythTv Service API Server Reaching").addHeader("Connection", "Close")
            .build();/*ww  w. j ava  2 s.c  o m*/
    Response response = client.newCall(request).execute();
    return response.isSuccessful();
}

From source file:org.sufficientlysecure.keychain.keyimport.FacebookKeyserver.java

License:Open Source License

private String query(String fbUsername) throws QueryFailedException {
    try {/*from w  w  w. ja  v a2  s .c  o m*/
        String request = String.format(FB_KEY_URL_FORMAT, fbUsername);
        Log.d(Constants.TAG, "fetching from Facebook with: " + request + " proxy: " + mProxy);

        OkHttpClient client = new OkHttpClient();
        client.setProxy(mProxy);

        URL url = new URL(request);

        Response response = client.newCall(new Request.Builder().url(url).build()).execute();

        // contains body both in case of success or failure
        String responseBody = response.body().string();

        if (response.isSuccessful()) {
            return responseBody;
        } else {
            // probably a 404 indicating that the key does not exist
            throw new QueryFailedException("key for " + fbUsername + " not found on Facebook");
        }

    } catch (IOException e) {
        Log.e(Constants.TAG, "IOException at Facebook key download", e);
        throw new QueryFailedException("Cannot connect to Facebook. " + "Check your Internet connection!"
                + (mProxy == Proxy.NO_PROXY ? "" : " Using proxy " + mProxy));
    }
}

From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyserver.java

License:Apache License

private String query(String request, @NonNull Proxy proxy) throws QueryFailedException, HttpError {
    try {//from   w  w  w  .j av a 2s.  c om
        URL url = new URL(getUrlPrefix() + mHost + ":" + mPort + request);
        Log.d(Constants.TAG, "hkp keyserver query: " + url + " Proxy: " + proxy);
        OkHttpClient client = getClient(url, proxy);
        Response response = client.newCall(new Request.Builder().url(url).build()).execute();

        String responseBody = response.body().string(); // contains body both in case of success or failure

        if (response.isSuccessful()) {
            return responseBody;
        } else {
            throw new HttpError(response.code(), responseBody);
        }
    } catch (IOException e) {
        Log.e(Constants.TAG, "IOException at HkpKeyserver", e);
        throw new QueryFailedException(
                "Keyserver '" + mHost + "' is unavailable. Check your Internet connection!"
                        + (proxy == Proxy.NO_PROXY ? "" : " Using proxy " + proxy));
    }
}

From source file:org.sufficientlysecure.keychain.ui.dialog.AddEditKeyserverDialogFragment.java

License:Open Source License

public void verifyConnection(String keyserver, final Proxy proxy, final boolean onlyTrustedKeyserver) {

    new AsyncTask<String, Void, FailureReason>() {
        ProgressDialog mProgressDialog;/*from  w  w  w .j  av  a2  s  .  c o m*/
        String mKeyserver;

        @Override
        protected void onPreExecute() {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setMessage(getString(R.string.progress_verifying_keyserver_connection));
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
        }

        @Override
        protected FailureReason doInBackground(String... keyservers) {
            mKeyserver = keyservers[0];
            FailureReason reason = null;
            try {
                // replace hkps/hkp scheme and reconstruct Uri
                Uri keyserverUri = Uri.parse(mKeyserver);
                String scheme = keyserverUri.getScheme();
                String schemeSpecificPart = keyserverUri.getSchemeSpecificPart();
                String fragment = keyserverUri.getFragment();
                if (scheme == null) {
                    throw new MalformedURLException();
                }
                if ("hkps".equalsIgnoreCase(scheme)) {
                    scheme = "https";
                } else if ("hkp".equalsIgnoreCase(scheme)) {
                    scheme = "http";
                }
                URI newKeyserver = new URI(scheme, schemeSpecificPart, fragment);

                Log.d("Converted URL", newKeyserver.toString());

                OkHttpClient client = HkpKeyserver.getClient(newKeyserver.toURL(), proxy);

                // don't follow any redirects
                client.setFollowRedirects(false);
                client.setFollowSslRedirects(false);

                if (onlyTrustedKeyserver
                        && !TlsHelper.usePinnedCertificateIfAvailable(client, newKeyserver.toURL())) {
                    Log.w(Constants.TAG, "No pinned certificate for this host in OpenKeychain's assets.");
                    reason = FailureReason.NO_PINNED_CERTIFICATE;
                    return reason;
                }

                client.newCall(new Request.Builder().url(newKeyserver.toURL()).build()).execute();
            } catch (TlsHelper.TlsHelperException e) {
                reason = FailureReason.CONNECTION_FAILED;
            } catch (MalformedURLException | URISyntaxException e) {
                Log.w(Constants.TAG, "Invalid keyserver URL entered by user.");
                reason = FailureReason.INVALID_URL;
            } catch (IOException e) {
                Log.w(Constants.TAG, "Could not connect to entered keyserver url");
                reason = FailureReason.CONNECTION_FAILED;
            }
            return reason;
        }

        @Override
        protected void onPostExecute(FailureReason failureReason) {
            mProgressDialog.dismiss();
            if (failureReason == null) {
                keyserverEdited(mKeyserver, true);
            } else {
                verificationFailed(failureReason);
            }
        }
    }.execute(keyserver);
}

From source file:org.tecrash.crashreport.DropboxUploadingJob.java

License:Open Source License

@Override
public void onRun() throws Throwable {
    long last = Util.getLastEntryTimestamp(); // ??
    if (!Build.VERSION.INCREMENTAL.equals(incremental)) {
        // ??drpbox entry??
        long bootTime = System.currentTimeMillis() - SystemClock.elapsedRealtime();
        if (bootTime > last) {
            last = bootTime;/*from ww w. j  a v a  2  s  .  c o  m*/
            Util.setLastEntryTimestamp(last);
        }
    }
    //        if (last >= timestamp) {
    //            logger.d("Cancelled as it was reported before!");
    //            return;
    //        }
    if (!Util.isEnabled()) {
        logger.d("Disabled so cancel it!");
        Util.setLastEntryTimestamp(last);
        return;
    }

    DropBoxManager dbm = (DropBoxManager) ReportApp.getInstance().getSystemService(Context.DROPBOX_SERVICE);
    List<ReportDatas.Entry> datas = new ArrayList<ReportDatas.Entry>();
    List<Long> timestamps = new ArrayList<Long>();
    List<String> tags = new ArrayList<String>();
    List<Long> entryTimestamps = new ArrayList<Long>();

    for (String tag : Util.getTags().keySet()) {
        DropBoxManager.Entry entry = dbm.getNextEntry(tag, last);
        while (entry != null) {
            ReportDatas.Entry data = convertToReportEntry(entry);
            if (data != null) {
                boolean found = false;
                for (ReportDatas.Entry d : datas) {
                    if (d.tag.equals(data.tag) && d.app.equals(data.app)) {
                        d.data.count += data.data.count;
                        if (d.data.count > 5)
                            d.data.count = 5;
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    datas.add(data);
                    timestamps.add(last);
                    tags.add(tag);
                }
            }
            last = entry.getTimeMillis();
            entryTimestamps.add(last);
            entry = dbm.getNextEntry(tag, last);
        }
        //set back to last saved, for next tag
        last = Util.getLastEntryTimestamp();
    }

    IDropboxService service = getReportService(Util.getURL());

    // report dropbox entries
    ReportDatas.ReportResults results = service.report(Util.getKey(), Util.getUserAgent(),
            new ReportDatas(datas));

    //set the latest entry's timestamp as last
    if (!entryTimestamps.isEmpty()) {
        Collections.sort(entryTimestamps);
        last = entryTimestamps.get(entryTimestamps.size() - 1);
    }
    // save where to upload next time.
    Util.setLastEntryTimestamp(last);

    //check whether to report full dropbox entry content and log
    if (shouldReportDetail()) {
        for (int i = 0; i < results.data.length; i++) {
            ReportDatas.Result result = results.data[i];
            ReportDatas.Entry data = datas.get(i);
            if (result != null && result.dropbox_id != null && result.dropbox_id.length() > 0) {
                DropBoxManager.Entry entry = dbm.getNextEntry(tags.get(i), timestamps.get(i));
                // use okhttp to gzip content
                OkHttpClient client = new OkHttpClient();
                client.networkInterceptors().add(new GzipRequestInterceptor());
                RequestBody requestBody = new StreamRequestBody(entry.getInputStream());
                Request request = new Request.Builder()
                        .url(Util.getURL() + "/dropbox/" + result.dropbox_id + "/content")
                        .header("Authorization", Util.getKey()).post(requestBody).build();
                client.newCall(request).execute();
            }
        }
        IDropboxService uploadService = getReportService(Util.getUploadURL());
        for (int i = 0; i < results.data.length; i++) {
            ReportDatas.Result result = results.data[i];
            if (result != null && result.dropbox_id != null && result.dropbox_id.length() > 0) { // server received the data
                // upload attachment
                ReportDatas.Entry data = datas.get(i);
                if (data.data.log != null && data.data.log.length() > 0
                        && (data.data.log.endsWith(".gz") || data.data.log.endsWith(".zip"))) {
                    File file = new File(data.data.log);
                    if (file.exists()) {
                        uploadService.uploadAttachment(Util.getKey(), result.dropbox_id,
                                new TypedFile("application/zip", file));
                    }
                }
            }
        }
    }
    logger.d("** Total %d Dropbox entries added!", results.data.length);
}

From source file:org.tinymediamanager.ui.dialogs.BugReportDialog.java

License:Apache License

private void sendBugReport() throws Exception {
    OkHttpClient client = TmmHttpClient.getHttpClient();
    String url = "https://script.google.com/macros/s/AKfycbzrhTmZiHJb1bdCqyeiVOqLup8zK4Dbx6kAtHYsgzBVqHTaNJqj/exec";

    StringBuilder message = new StringBuilder("Bug report from ");
    message.append(tfName.getText());//from  ww  w  .  j a  v  a2 s  .c  o m
    message.append("\nEmail:");
    message.append(tfEmail.getText());
    message.append("\n");
    message.append("\nis Donator?: ");
    message.append(Globals.isDonator());
    message.append("\nVersion: ");
    message.append(ReleaseInfo.getRealVersion());
    message.append("\nBuild: ");
    message.append(ReleaseInfo.getRealBuildDate());
    message.append("\nOS: ");
    message.append(System.getProperty("os.name"));
    message.append(" ");
    message.append(System.getProperty("os.version"));
    message.append("\nJDK: ");
    message.append(System.getProperty("java.version"));
    message.append(" ");
    message.append(System.getProperty("java.vendor"));
    message.append("\nUUID: ");
    message.append(System.getProperty("tmm.uuid"));
    message.append("\n\n");
    message.append(textArea.getText());

    BugReportDialog.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

    MultipartBuilder multipartBuilder = new MultipartBuilder();
    multipartBuilder.type(MultipartBuilder.FORM);

    multipartBuilder.addPart(Headers.of("Content-Disposition", "form-data; name=\"message\""),
            RequestBody.create(null, message.toString()));
    multipartBuilder.addPart(Headers.of("Content-Disposition", "form-data; name=\"sender\""),
            RequestBody.create(null, tfEmail.getText()));

    // attach files
    try {
        // build zip with selected files in it
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(os);

        // attach logs
        File[] logs = new File("logs").listFiles(new FilenameFilter() {
            Pattern logPattern = Pattern.compile("tmm\\.log\\.*");

            @Override
            public boolean accept(File directory, String filename) {
                Matcher matcher = logPattern.matcher(filename);
                if (matcher.find()) {
                    return true;
                }
                return false;
            }
        });
        if (logs != null) {
            for (File logFile : logs) {
                try {
                    FileInputStream in = new FileInputStream(logFile);
                    ZipEntry ze = new ZipEntry(logFile.getName());
                    zos.putNextEntry(ze);

                    IOUtils.copy(in, zos);
                    in.close();
                    zos.closeEntry();
                } catch (Exception e) {
                    LOGGER.warn("unable to attach " + logFile.getName() + ": " + e.getMessage());
                }
            }
        }

        try {
            FileInputStream in = new FileInputStream("launcher.log");
            ZipEntry ze = new ZipEntry("launcher.log");
            zos.putNextEntry(ze);

            IOUtils.copy(in, zos);
            in.close();
            zos.closeEntry();
        } catch (Exception e) {
            LOGGER.warn("unable to attach launcher.log: " + e.getMessage());
        }

        // attach config file
        try {
            ZipEntry ze = new ZipEntry("config.xml");
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(
                    new File(Settings.getInstance().getSettingsFolder(), "config.xml"));

            IOUtils.copy(in, zos);
            in.close();
            zos.closeEntry();
        } catch (Exception e) {
            LOGGER.warn("unable to attach config.xml: " + e.getMessage());
        }

        zos.close();

        byte[] data = os.toByteArray();
        String data_string = Base64.encodeBase64String(data);
        multipartBuilder.addPart(Headers.of("Content-Disposition", "form-data; name=\"logs\""),
                RequestBody.create(null, data_string));
    } catch (IOException ex) {
        LOGGER.warn("error adding attachments", ex);
    }
    Request request = new Request.Builder().url(url).post(multipartBuilder.build()).build();
    client.newCall(request).execute();
}

From source file:org.tinymediamanager.ui.dialogs.FeedbackDialog.java

License:Apache License

/**
 * Instantiates a new feedback dialog.//www .j a v  a 2  s  . c om
 */
public FeedbackDialog() {
    super(BUNDLE.getString("Feedback"), "feedback"); //$NON-NLS-1$
    setBounds(100, 100, 450, 320);

    getContentPane().setLayout(new FormLayout(
            new ColumnSpec[] { FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(400px;min):grow"),
                    FormFactory.RELATED_GAP_COLSPEC, },
            new RowSpec[] { FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("fill:max(250px;min):grow"),
                    FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
                    FormFactory.RELATED_GAP_ROWSPEC, }));

    JPanel panelContent = new JPanel();
    getContentPane().add(panelContent, "2, 2, fill, fill");
    panelContent.setLayout(new FormLayout(
            new ColumnSpec[] { FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC,
                    FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow"),
                    FormFactory.RELATED_GAP_COLSPEC, },
            new RowSpec[] { FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
                    FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
                    FormFactory.PARAGRAPH_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
                    FormFactory.NARROW_LINE_GAP_ROWSPEC, RowSpec.decode("default:grow"), }));

    JLabel lblName = new JLabel(BUNDLE.getString("Feedback.name")); //$NON-NLS-1$
    panelContent.add(lblName, "2, 2, right, default");

    tfName = new JTextField();
    panelContent.add(tfName, "4, 2, fill, default");
    tfName.setColumns(10);

    JLabel lblEmailoptional = new JLabel(BUNDLE.getString("Feedback.email")); //$NON-NLS-1$
    panelContent.add(lblEmailoptional, "2, 4, right, default");

    tfEmail = new JTextField();
    panelContent.add(tfEmail, "4, 4, fill, default");
    tfEmail.setColumns(10);

    // pre-fill dialog
    if (Globals.isDonator()) {
        Properties p = License.decrypt();
        tfEmail.setText(p.getProperty("email"));
        tfName.setText(p.getProperty("user"));
    }

    JLabel lblFeedback = new JLabel(BUNDLE.getString("Feedback.message")); //$NON-NLS-1$
    panelContent.add(lblFeedback, "2, 6, 3, 1");

    JScrollPane scrollPane = new JScrollPane();
    panelContent.add(scrollPane, "2, 8, 3, 1, fill, fill");

    textArea = new JTextArea();
    scrollPane.setViewportView(textArea);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);

    JPanel panelButtons = new JPanel();
    panelButtons.setLayout(new EqualsLayout(5));
    getContentPane().add(panelButtons, "2, 4, fill, fill");

    JButton btnSend = new JButton(BUNDLE.getString("Feedback")); //$NON-NLS-1$
    btnSend.setIcon(IconManager.APPLY);
    btnSend.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            // check if feedback is provided
            if (StringUtils.isEmpty(textArea.getText())) {
                JOptionPane.showMessageDialog(null, BUNDLE.getString("Feedback.message.empty")); //$NON-NLS-1$
                return;
            }

            // send feedback
            OkHttpClient client = TmmHttpClient.getHttpClient();
            String url = "https://script.google.com/macros/s/AKfycbxTIhI58gwy0UJ0Z1CdmZDdHlwBDU_vugBmQxcKN9aug4nfgrgZ/exec";

            try {
                StringBuilder message = new StringBuilder("Feedback from ");
                message.append(tfName.getText());
                message.append("\nEmail:");
                message.append(tfEmail.getText());
                message.append("\n");
                message.append("\nis Donator?: ");
                message.append(Globals.isDonator());
                message.append("\nVersion: ");
                message.append(ReleaseInfo.getRealVersion());
                message.append("\nBuild: ");
                message.append(ReleaseInfo.getRealBuildDate());
                message.append("\nOS: ");
                message.append(System.getProperty("os.name"));
                message.append(" ");
                message.append(System.getProperty("os.version"));
                message.append("\nJDK: ");
                message.append(System.getProperty("java.version"));
                message.append(" ");
                message.append(System.getProperty("java.vendor"));
                message.append("\nUUID: ");
                message.append(System.getProperty("tmm.uuid"));
                message.append("\n\n");
                message.append(textArea.getText());

                MultipartBuilder multipartBuilder = new MultipartBuilder();
                multipartBuilder.type(MultipartBuilder.FORM);

                multipartBuilder.addPart(Headers.of("Content-Disposition", "form-data; name=\"message\""),
                        RequestBody.create(null, message.toString()));
                multipartBuilder.addPart(Headers.of("Content-Disposition", "form-data; name=\"sender\""),
                        RequestBody.create(null, tfEmail.getText()));

                Request request = new Request.Builder().url(url).post(multipartBuilder.build()).build();
                client.newCall(request).execute();
            } catch (IOException e) {
                LOGGER.error("failed sending feedback: " + e.getMessage());
                JOptionPane.showMessageDialog(null,
                        BUNDLE.getString("Feedback.send.error") + "\n" + e.getMessage()); //$NON-NLS-1$
                return;
            }

            JOptionPane.showMessageDialog(null, BUNDLE.getString("Feedback.send.ok")); //$NON-NLS-1$
            setVisible(false);
        }
    });
    panelButtons.add(btnSend);

    JButton btnCacnel = new JButton(BUNDLE.getString("Button.cancel")); //$NON-NLS-1$
    btnCacnel.setIcon(IconManager.CANCEL);
    btnCacnel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
        }
    });
    panelButtons.add(btnCacnel);
}

From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java

private Response getConnection(String urlFragment, String method, String body) throws PushNetworkException {
    try {// w w  w. j a v  a  2s. com
        Log.w(TAG, "Push service URL: " + serviceUrl);
        Log.w(TAG, "Opening URL: " + String.format("%s%s", serviceUrl, urlFragment));

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, null);

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(context.getSocketFactory());
        okHttpClient.setHostnameVerifier(new StrictHostnameVerifier());

        Request.Builder request = new Request.Builder();
        request.url(String.format("%s%s", serviceUrl, urlFragment));

        if (body != null) {
            request.method(method, RequestBody.create(MediaType.parse("application/json"), body));
        } else {
            request.method(method, null);
        }

        if (credentialsProvider.getPassword() != null) {
            request.addHeader("Authorization", getAuthorizationHeader());
        }

        if (userAgent != null) {
            request.addHeader("X-Signal-Agent", userAgent);
        }

        return okHttpClient.newCall(request.build()).execute();
    } catch (IOException e) {
        throw new PushNetworkException(e);
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new AssertionError(e);
    }
}

From source file:org.wildfly.kubernetes.configmap.ConfigMapOperations.java

License:Open Source License

public void createConfigMap(OkHttpClient client, String namespace, String name, Map<String, String> labels,
        Collection<Path> files) throws IOException {
    Request request = new Request.Builder().url(buildUrl(namespace, null))
            .post(createJsonPayload(namespace, name, labels, files)).build();
    Response response = client.newCall(request).execute();
    if (HttpURLConnection.HTTP_CREATED != response.code()) {
        readStatusResponse(response);//from  ww w  .  j  av a 2  s  .co m
    }
}

From source file:org.wildfly.kubernetes.configmap.ConfigMapOperations.java

License:Open Source License

public void deleteConfigMap(OkHttpClient client, String namespace, String name) throws IOException {
    Request request = new Request.Builder().url(buildUrl(namespace, name)).delete().build();
    Response response = client.newCall(request).execute();
    if (HttpURLConnection.HTTP_OK != response.code()) {
        readStatusResponse(response);/*from   ww w.ja v  a2 s.c o  m*/
    }
}