Example usage for com.squareup.okhttp MultipartBuilder MultipartBuilder

List of usage examples for com.squareup.okhttp MultipartBuilder MultipartBuilder

Introduction

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

Prototype

public MultipartBuilder() 

Source Link

Document

Creates a new multipart builder that uses a random boundary token.

Usage

From source file:de.ebf.UploadFileOneSkyAppMojo.java

License:Apache License

private void uploadFiles() throws MojoExecutionException {
    try {//from   www.j  a  va 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:io.kodokojo.service.marathon.MarathonConfigurationStore.java

License:Open Source License

@Override
public boolean storeBootstrapStackData(BootstrapStackData bootstrapStackData) {
    if (bootstrapStackData == null) {
        throw new IllegalArgumentException("bootstrapStackData must be defined.");
    }/*from w  ww  .  j av a2 s.  c o  m*/
    String url = marathonUrl + "/v2/artifacts/config/" + bootstrapStackData.getProjectName().toLowerCase()
            + ".json";
    OkHttpClient httpClient = new OkHttpClient();
    Gson gson = new GsonBuilder().create();
    String json = gson.toJson(bootstrapStackData);
    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
            .addFormDataPart("file", bootstrapStackData.getProjectName().toLowerCase() + ".json",
                    RequestBody.create(MediaType.parse("application/json"), json.getBytes()))
            .build();
    Request request = new Request.Builder().url(url).post(requestBody).build();
    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        return response.code() == 200;
    } catch (IOException e) {
        LOGGER.error("Unable to store configuration for project {}", bootstrapStackData.getProjectName(), e);
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    return false;
}

From source file:io.kodokojo.service.marathon.MarathonConfigurationStore.java

License:Open Source License

@Override
public boolean storeSSLKeys(String project, String entityName, SSLKeyPair sslKeyPair) {
    if (isBlank(project)) {
        throw new IllegalArgumentException("project must be defined.");
    }/*from ww w.j av a2s. c o  m*/
    if (isBlank(entityName)) {
        throw new IllegalArgumentException("entityName must be defined.");
    }
    if (sslKeyPair == null) {
        throw new IllegalArgumentException("sslKeyPair must be defined.");
    }
    Response response = null;
    try {
        Writer writer = new StringWriter();
        SSLUtils.writeSSLKeyPairPem(sslKeyPair, writer);
        byte[] certificat = writer.toString().getBytes();

        String url = marathonUrl + "/v2/artifacts/ssl/" + project.toLowerCase() + "/" + entityName.toLowerCase()
                + "/" + project.toLowerCase() + "-" + entityName.toLowerCase() + "-server.pem";
        OkHttpClient httpClient = new OkHttpClient();
        RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                .addFormDataPart("file", project + "-" + entityName + "-server.pem",
                        RequestBody.create(MediaType.parse("application/text"), certificat))
                .build();
        Request request = new Request.Builder().url(url).post(requestBody).build();
        response = httpClient.newCall(request).execute();
        int code = response.code();
        if (code > 200 && code < 300) {
            LOGGER.info("Push SSL certificate on marathon url '{}' [content-size={}]", url, certificat.length);
        } else {
            LOGGER.error("Fail to push SSL certificate on marathon url '{}' status code {}. Body response:\n{}",
                    url, code, response.body().string());
        }
        return code > 200 && code < 300;
    } catch (IOException e) {
        LOGGER.error("Unable to store ssl key for project {} and brick {}", project, entityName, e);
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    return false;
}

From source file:net.qiujuer.common.okhttp.impl.RequestCallBuilder.java

License:Apache License

protected RequestBody createMultipartBody(StrParam[] stringStrParams, IOParam[] IOParams) {
    MultipartBuilder builder = new MultipartBuilder();
    builder.type(MultipartBuilder.FORM);
    builder = buildMultipartBody(builder);

    if (stringStrParams != null && stringStrParams.length > 0) {
        for (StrParam strParam : stringStrParams) {
            if (strParam.key != null && strParam.value != null) {
                builder.addFormDataPart(strParam.key, strParam.value);
                log("buildMultiStringParam: key: " + strParam.key + " value: " + strParam.value);
            } else {
                log("buildMultiStringParam: key: " + (strParam.key != null ? strParam.key : "null") + " value: "
                        + (strParam.value != null ? strParam.value : "null"));
            }//from   www  .j  av a  2 s  .  c o  m
        }
    }

    if (IOParams != null && IOParams.length > 0) {
        for (IOParam param : IOParams) {
            if (param.key != null && param.file != null) {
                String fileName = param.file.getName();
                RequestBody fileBody = RequestBody.create(MediaType.parse(Util.getFileMimeType(fileName)),
                        param.file);
                builder.addFormDataPart(param.key, fileName, fileBody);
                log("buildMultiFileParam: key: " + param.key + " value: " + fileName);
            } else {
                log("buildMultiFileParam: key: " + (param.key != null ? param.key : "null") + " file: "
                        + (param.file != null ? param.file.getName() : "null"));
            }
        }
    }
    return builder.build();
}

From source file:org.catrobat.catroid.web.ServerCalls.java

License:Open Source License

public void uploadProject(String projectName, String projectDescription, String zipFileString, String userEmail,
        String language, String token, String username, ResultReceiver receiver, Integer notificationId,
        Context context) throws WebconnectionException {

    Preconditions.checkNotNull(context, "Context cannot be null!");

    userEmail = emailForUiTests == null ? userEmail : emailForUiTests;
    userEmail = userEmail == null ? "" : userEmail;

    try {/*www . j a v a 2 s  .  c om*/
        String md5Checksum = Utils.md5Checksum(new File(zipFileString));

        final String serverUrl = useTestUrl ? TEST_FILE_UPLOAD_URL_HTTP : FILE_UPLOAD_URL;

        Log.v(TAG, "Url to upload: " + serverUrl);

        File file = new File(zipFileString);
        RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                .addFormDataPart(FILE_UPLOAD_TAG, ProjectUploadService.UPLOAD_FILE_NAME,
                        RequestBody.create(MEDIA_TYPE_ZIPFILE, file))
                .addFormDataPart(PROJECT_NAME_TAG, projectName)
                .addFormDataPart(PROJECT_DESCRIPTION_TAG, projectDescription)
                .addFormDataPart(USER_EMAIL, userEmail).addFormDataPart(PROJECT_CHECKSUM_TAG, md5Checksum)
                .addFormDataPart(Constants.TOKEN, token).addFormDataPart(Constants.USERNAME, username)
                .addFormDataPart(DEVICE_LANGUAGE, language).build();

        Request request = new Request.Builder().url(serverUrl).post(requestBody).build();

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

        if (response.isSuccessful()) {
            Log.v(TAG, "Upload successful");
            StatusBarNotificationManager.getInstance().showOrUpdateNotification(notificationId, 100);
        } else {
            Log.v(TAG, "Upload not successful");
            throw new WebconnectionException(response.code(),
                    "Upload failed! HTTP Status code was " + response.code());
        }

        UploadResponse uploadResponse = gson.fromJson(response.body().string(), UploadResponse.class);

        String newToken = uploadResponse.token;
        String answer = uploadResponse.answer;
        int status = uploadResponse.statusCode;
        projectId = uploadResponse.projectId;

        if (status != SERVER_RESPONSE_TOKEN_OK) {
            throw new WebconnectionException(status, "Upload failed! JSON Response was " + status);
        }

        if (token.length() != TOKEN_LENGTH || token.isEmpty() || token.equals(TOKEN_CODE_INVALID)) {
            throw new WebconnectionException(status, answer);
        }
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        sharedPreferences.edit().putString(Constants.TOKEN, newToken).commit();
        sharedPreferences.edit().putString(Constants.USERNAME, username).commit();
    } catch (JsonSyntaxException jsonSyntaxException) {
        Log.e(TAG, Log.getStackTraceString(jsonSyntaxException));
        throw new WebconnectionException(WebconnectionException.ERROR_JSON, "JsonSyntaxException");
    } catch (IOException ioException) {
        Log.e(TAG, Log.getStackTraceString(ioException));
        throw new WebconnectionException(WebconnectionException.ERROR_NETWORK, "I/O Exception");
    }
}

From source file:org.floens.chan.core.http.ReplyHttpCall.java

License:Open Source License

@Override
public void setup(Request.Builder requestBuilder) {
    boolean thread = reply.resto >= 0;

    password = Long.toHexString(RANDOM.nextLong());

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

    formBuilder.addFormDataPart("mode", "regist");
    formBuilder.addFormDataPart("pwd", password);

    if (thread) {
        formBuilder.addFormDataPart("resto", String.valueOf(reply.resto));
    }//from   w ww .j  a v a  2  s .  c o m

    formBuilder.addFormDataPart("name", reply.name);
    formBuilder.addFormDataPart("email", reply.options);

    if (!thread && !TextUtils.isEmpty(reply.subject)) {
        formBuilder.addFormDataPart("sub", reply.subject);
    }

    formBuilder.addFormDataPart("com", reply.comment);

    if (reply.captchaResponse != null) {
        if (reply.captchaChallenge != null) {
            formBuilder.addFormDataPart("recaptcha_challenge_field", reply.captchaChallenge);
            formBuilder.addFormDataPart("recaptcha_response_field", reply.captchaResponse);
        } else {
            formBuilder.addFormDataPart("g-recaptcha-response", reply.captchaResponse);
        }
    }

    if (reply.file != null) {
        formBuilder.addFormDataPart("upfile", reply.fileName,
                RequestBody.create(MediaType.parse("application/octet-stream"), reply.file));
    }

    if (reply.spoilerImage) {
        formBuilder.addFormDataPart("spoiler", "on");
    }

    requestBuilder.url(ChanUrls.getReplyUrl(reply.board));
    requestBuilder.post(formBuilder.build());

    if (reply.usePass) {
        requestBuilder.addHeader("Cookie", "pass_id=" + reply.passId);
    }
}

From source file:org.floens.chan.core.manager.ReplyManager.java

License:Open Source License

private void postReplyInternal(final Reply reply, final ReplyListener replyListener, String captchaHash) {
    reply.password = Long.toHexString(random.nextLong());

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

    formBuilder.addFormDataPart("mode", "regist");
    formBuilder.addFormDataPart("pwd", reply.password);

    if (reply.resto >= 0) {
        formBuilder.addFormDataPart("resto", String.valueOf(reply.resto));
    }/*from www  .  ja  v a  2 s .  c o m*/

    formBuilder.addFormDataPart("name", reply.name);
    formBuilder.addFormDataPart("email", reply.email);

    if (!TextUtils.isEmpty(reply.subject)) {
        formBuilder.addFormDataPart("sub", reply.subject);
    }

    formBuilder.addFormDataPart("com", reply.comment);

    if (captchaHash != null) {
        formBuilder.addFormDataPart("g-recaptcha-response", captchaHash);
    }

    if (reply.file != null) {
        formBuilder.addFormDataPart("upfile", reply.fileName,
                RequestBody.create(MediaType.parse("application/octet-stream"), reply.file));
    }

    if (reply.spoilerImage) {
        formBuilder.addFormDataPart("spoiler", "on");
    }

    Request.Builder request = new Request.Builder().url(ChanUrls.getReplyUrl(reply.board))
            .post(formBuilder.build());

    if (reply.usePass) {
        request.addHeader("Cookie", "pass_id=" + reply.passId);
    }

    makeOkHttpCall(request, new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            final ReplyResponse res = new ReplyResponse();
            res.isNetworkError = true;

            runUI(new Runnable() {
                public void run() {
                    replyListener.onResponse(res);
                }
            });
        }

        @Override
        public void onResponse(Response response) throws IOException {
            final ReplyResponse res = new ReplyResponse();
            if (response.isSuccessful()) {
                onReplyPosted(response.body().string(), reply, res);
                response.body().close();
            } else {
                res.isNetworkError = true;
            }

            runUI(new Runnable() {
                public void run() {
                    replyListener.onResponse(res);
                }
            });
        }
    });
}

From source file:org.getlantern.firetweet.extension.streaming.util.OkHttpClientImpl.java

License:Open Source License

private RequestBody getRequestBody(HttpParameter[] params) throws IOException {
    if (params == null)
        return null;
    if (!HttpParameter.containsFile(params)) {
        return RequestBody.create(APPLICATION_FORM_URLENCODED, HttpParameter.encodeParameters(params));
    }/*from  www .j a v  a2 s . c o m*/
    final MultipartBuilder builder = new MultipartBuilder();
    builder.type(MultipartBuilder.FORM);
    for (final HttpParameter param : params) {
        if (param.isFile()) {
            RequestBody requestBody;
            if (param.hasFileBody()) {
                requestBody = new StreamRequestBody(MediaType.parse(param.getContentType()),
                        param.getFileBody(), true);
            } else {
                requestBody = RequestBody.create(MediaType.parse(param.getContentType()), param.getFile());
            }
            builder.addFormDataPart(param.getName(), param.getFileName(), requestBody);
        } else {
            builder.addFormDataPart(param.getName(), param.getValue());
        }
    }
    return builder.build();
}

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  w  w . j a v  a2  s.  c  om*/
        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.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 .ja va 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();
}