Example usage for com.squareup.okhttp RequestBody create

List of usage examples for com.squareup.okhttp RequestBody create

Introduction

In this page you can find the example usage for com.squareup.okhttp RequestBody create.

Prototype

public static RequestBody create(final MediaType contentType, final File file) 

Source Link

Document

Returns a new request body that transmits the content of file .

Usage

From source file:org.opensilk.music.library.drive.transport.OkLowLevelHttpRequest.java

License:Open Source License

@Override
public LowLevelHttpResponse execute() throws IOException {
    if (getStreamingContent() != null) {
        String contentType = getContentType();
        String contentEncoding = getContentEncoding();
        if (contentEncoding != null) {
            addHeader("Content-Encoding", contentEncoding);
        }//from   w ww.  ja  va2s.com
        long contentLength = getContentLength();
        //TODO handle upload properly
        ByteArrayOutputStream out = new ByteArrayOutputStream(contentLength > 0 ? (int) contentLength : 1024);
        try {
            getStreamingContent().writeTo(out);
            MediaType mediaType = MediaType.parse(contentType);
            RequestBody body = RequestBody.create(mediaType, out.toByteArray());
            builder.method(method, body);
        } finally {
            out.close();
        }
    } else {
        builder.method(method, null);
    }
    Response response = okClient.newCall(builder.build()).execute();
    return new OkLowLevelHttpResponse(response);
}

From source file:org.quantumbadger.redreader.http.okhttp.OKHTTPBackend.java

License:Open Source License

@Override
public Request prepareRequest(final Context context, final RequestDetails details) {

    final com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder();

    builder.header("User-Agent", Constants.ua(context));

    final List<PostField> postFields = details.getPostFields();

    if (postFields != null) {
        builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
                PostField.encodeList(postFields)));

    } else {/* www. j a v a 2 s . com*/
        builder.get();
    }

    builder.url(details.getUrl().toString());
    builder.cacheControl(CacheControl.FORCE_NETWORK);

    final AtomicReference<Call> callRef = new AtomicReference<>();

    return new Request() {

        public void executeInThisThread(final Listener listener) {

            final Call call = mClient.newCall(builder.build());
            callRef.set(call);

            try {

                final Response response;

                try {
                    response = call.execute();
                } catch (IOException e) {
                    listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, e, null);
                    return;
                }

                final int status = response.code();

                if (status == 200 || status == 202) {

                    final ResponseBody body = response.body();
                    final InputStream bodyStream;
                    final Long bodyBytes;

                    if (body != null) {
                        bodyStream = body.byteStream();
                        bodyBytes = body.contentLength();

                    } else {
                        // TODO error
                        bodyStream = null;
                        bodyBytes = null;
                    }

                    final String contentType = response.header("Content-Type");

                    listener.onSuccess(contentType, bodyBytes, bodyStream);

                } else {
                    listener.onError(CacheRequest.REQUEST_FAILURE_REQUEST, null, status);
                }

            } catch (Throwable t) {
                listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, t, null);
            }
        }

        @Override
        public void cancel() {
            final Call call = callRef.getAndSet(null);
            if (call != null) {
                call.cancel();
            }
        }

        @Override
        public void addHeader(final String name, final String value) {
            builder.addHeader(name, value);
        }
    };
}

From source file:org.sonarqube.ws.client.HttpConnector.java

License:Open Source License

private WsResponse post(PostRequest postRequest) {
    HttpUrl.Builder urlBuilder = prepareUrlBuilder(postRequest);
    Request.Builder okRequestBuilder = prepareOkRequestBuilder(postRequest, urlBuilder);

    Map<String, PostRequest.Part> parts = postRequest.getParts();
    if (parts.isEmpty()) {
        okRequestBuilder.post(RequestBody.create(null, ""));
    } else {/*from  w  ww .j  a va2 s .co m*/
        MultipartBuilder body = new MultipartBuilder().type(MultipartBuilder.FORM);
        for (Map.Entry<String, PostRequest.Part> param : parts.entrySet()) {
            PostRequest.Part part = param.getValue();
            body.addPart(Headers.of("Content-Disposition", format("form-data; name=\"%s\"", param.getKey())),
                    RequestBody.create(MediaType.parse(part.getMediaType()), part.getFile()));
        }
        okRequestBuilder.post(body.build());
    }

    return doCall(okRequestBuilder.build());
}

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

License:Apache License

@Override
public void add(String armoredKey) throws AddKeyException {
    try {/*from w  w w. jav  a 2  s. c  o  m*/
        String path = "/pks/add";
        String params;
        try {
            params = "keytext=" + URLEncoder.encode(armoredKey, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new AddKeyException();
        }
        URL url = new URL(getUrlPrefix() + mHost + ":" + mPort + path);

        Log.d(Constants.TAG, "hkp keyserver add: " + url);
        Log.d(Constants.TAG, "params: " + params);

        RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), params);

        Request request = new Request.Builder().url(url)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Content-Length", Integer.toString(params.getBytes().length)).post(body).build();

        Response response = getClient(url, mProxy).newCall(request).execute();

        Log.d(Constants.TAG, "response code: " + response.code());
        Log.d(Constants.TAG, "answer: " + response.body().string());

        if (response.code() != 200) {
            throw new AddKeyException();
        }

    } catch (IOException e) {
        Log.e(Constants.TAG, "IOException", e);
        throw new AddKeyException();
    }
}

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  w w w  . j a v  a  2  s . c om
    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 {/*from   w w w  .  j a va  2 s. co m*/
        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.wso2.carbon.identity.authenticator.duo.DuoHttp.java

License:Open Source License

public Response executeHttpRequest() throws Exception {
    String url = "https://" + host + uri;
    String queryString = createQueryString();
    Request.Builder builder = new Request.Builder();
    if (method.equals("POST")) {
        builder.post(RequestBody.create(FORM_ENCODED, queryString));
    } else if (method.equals("PUT")) {
        builder.put(RequestBody.create(FORM_ENCODED, queryString));
    } else if (method.equals("GET")) {
        if (queryString.length() > 0) {
            url += "?" + queryString;
        }//from www  .j a va 2  s  .  co  m
        builder.get();
    } else if (method.equals("DELETE")) {
        if (queryString.length() > 0) {
            url += "?" + queryString;
        }
        builder.delete();
    } else {
        throw new UnsupportedOperationException("Unsupported method: " + method);
    }
    Request request = builder.url(url).build();
    // Set up client.
    OkHttpClient httpclient = new OkHttpClient();
    if (proxy != null) {
        httpclient.setProxy(proxy);
    }
    httpclient.setConnectTimeout(timeout, TimeUnit.SECONDS);
    httpclient.setWriteTimeout(timeout, TimeUnit.SECONDS);
    httpclient.setReadTimeout(timeout, TimeUnit.SECONDS);
    // finish and execute request
    builder.headers(headers.build());
    return httpclient.newCall(builder.build()).execute();
}

From source file:org.xbmc.kore.jsonrpc.HostConnection.java

License:Open Source License

/**
 * Sends the JSON RPC request through HTTP (using OkHttp library)
 *//* w  w w .  j a  v a  2 s . c o  m*/
private <T> void executeThroughOkHttp(final ApiMethod<T> method, final ApiCallback<T> callback,
        final Handler handler) {
    OkHttpClient client = getOkHttpClient();
    String jsonRequest = method.toJsonString();

    try {
        Request request = new Request.Builder().url(hostInfo.getJsonRpcHttpEndpoint())
                .post(RequestBody.create(MEDIA_TYPE_JSON, jsonRequest)).build();
        LogUtils.LOGD(TAG, "Sending request via OkHttp: " + jsonRequest);
        Response response = sendOkHttpRequest(client, request);
        final T result = method.resultFromJson(parseJsonResponse(handleOkHttpResponse(response)));

        if ((handler != null) && (callback != null)) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onSuccess(result);
                }
            });
        }
    } catch (final ApiException e) {
        // Got an error, call error handler
        if ((handler != null) && (callback != null)) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onError(e.getCode(), e.getMessage());
                }
            });
        }
    }
}

From source file:pb.auth.OAuth.java

License:Apache License

public void generateAndSetAccessToken(String apiKey, String secret) throws ApiException {
    RequestBody body = RequestBody.create(MediaType.parse("application/json"), "grant_type=client_credentials");
    Request authRequest = null;/*  w ww  . j a  v  a  2 s . c om*/

    String authenticationHeader = base64Encode(apiKey + ":" + secret);
    authRequest = new Request.Builder().url("https://api.pitneybowes.com/oauth/token").post(body)
            .addHeader("Authorization", "Basic " + authenticationHeader).build();
    OkHttpClient client = new OkHttpClient().setAuthenticator(new TokenAuthenticator());

    try {
        Response response = client.newCall(authRequest).execute();
        Gson gson = new Gson();
        OAuthServiceResponce fromJson = gson.fromJson(response.body().string(), OAuthServiceResponce.class);
        setApiKey(apiKey);
        setSecret(secret);
        setAccessToken(fromJson.access_token);
    } catch (IOException e) {
        throw new ApiException(e);
    }

}