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:com.kkbox.toolkit.internal.api.APIRequest.java

License:Apache License

public void addMultiPartPostParam(String key, String value) {
    if (multipartBuilder == null) {
        multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
    }/* ww  w. ja v  a2s .co  m*/
    multipartBuilder.addFormDataPart(key, value);
}

From source file:com.lidroid.xutils.HttpUtils.java

License:Apache License

@NonNull
private RequestBody buildFileRequestBody(RequestParams params, HashMap<String, ContentBody> fileParams) {
    MultipartBuilder builder = new MultipartBuilder();

    builder = builder.type(MultipartBuilder.FORM);
    for (String fileName : fileParams.keySet()) {
        builder.addFormDataPart(fileName, fileName, RequestBody.create(
                MediaType.parse("application/octet-stream"), ((FileBody) fileParams.get(fileName)).getFile()));
    }//www.  j  a v  a  2  s  .  co m

    List<NameValuePair> bodyParams = params.getBodyParams();

    if (bodyParams != null) {
        for (NameValuePair param : params.getBodyParams()) {
            builder.addFormDataPart(param.getName(), param.getValue());
        }
    }

    return builder.build();
}

From source file:com.liferay.mobile.android.http.client.OkHttpClientImpl.java

License:Open Source License

protected RequestBody getUploadBody(Request request) {
    JSONObject body = (JSONObject) request.getBody();
    Object tag = request.getTag();

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

    Iterator<String> it = body.keys();

    while (it.hasNext()) {
        String key = it.next();/*  ww  w.  ja  v  a  2 s  .co m*/
        Object value = body.opt(key);

        if (value instanceof UploadData) {
            UploadData data = (UploadData) value;
            RequestBody requestBody = new InputStreamBody(data, tag);
            builder.addFormDataPart(key, data.getFileName(), requestBody);
        } else {
            builder.addFormDataPart(key, value.toString());
        }
    }

    return builder.build();
}

From source file:com.magnet.max.android.Attachment.java

License:Apache License

/**
 * Upload the attachment to Max Server/* w ww  . j  a  v  a2  s.c  o m*/
 * @param listener
 */
public void upload(final UploadListener listener) {
    if (StringUtil.isNotEmpty(mAttachmentId)) {
        // Already uploaded
        Log.d(TAG, "Already uploaded");
        if (null != listener) {
            listener.onComplete(this);
        }
        return;
    }

    if (mStatus == Status.INIT || mStatus == Status.ERROR) {
        if (null != listener) {
            listener.onStart(this);
        }

        final AtomicReference<Long> startTime = new AtomicReference<>();
        Callback<Map<String, String>> uploadCallback = new Callback<Map<String, String>>() {
            @Override
            public void onResponse(Response<Map<String, String>> response) {
                if (response.isSuccess()) {
                    Map<String, String> result = response.body();
                    if (null != result && !result.isEmpty()) {
                        mAttachmentId = result.values().iterator().next();
                        mStatus = Status.COMPLETE;
                        Log.d(TAG, "It took " + (System.currentTimeMillis() - startTime.get()) / 1000
                                + " seconds to upload attachment " + mAttachmentId);
                        if (null != listener) {
                            listener.onComplete(Attachment.this);
                        }
                    } else {
                        handleError(new Exception("Can't get attachmentId from response"));
                    }
                } else {
                    handleError(new Exception(response.message()));
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                handleError(throwable);
            }

            private void handleError(Throwable throwable) {
                mStatus = Status.ERROR;
                Log.d(TAG, "Failed to upload attachment " + mName, throwable);
                if (null != listener) {
                    listener.onError(Attachment.this, throwable);
                }
            }
        };

        RequestBody requestBody = null;
        if (mSourceType == ContentSourceType.FILE) {
            requestBody = RequestBody.create(MediaType.parse(getMimeType()), (File) mContent);
        } else {
            requestBody = RequestBody.create(MediaType.parse(getMimeType()), getAsBytes());
        }
        startTime.set(System.currentTimeMillis());

        String partName = StringUtil.isNotEmpty(mName) ? mName : "attachment";
        getAttachmentService()
                .uploadMultiple(mMetaData,
                        new MultipartBuilder().type(MultipartBuilder.FORM)
                                .addFormDataPart(partName, partName, requestBody).build(),
                        uploadCallback)
                .executeInBackground();

        mStatus = Status.TRANSFERING;
    } else if (mStatus == Status.TRANSFERING) {
        if (null != listener) {
            listener.onError(this, new IllegalStateException("Attachment is being uploading"));
        }
    }
}

From source file:com.mcxiaoke.next.http.NextRequest.java

License:Apache License

protected RequestBody getRequestBody() throws IOException {
    if (!supportBody()) {
        return null;
    }//from   w  ww.java  2  s . c  om
    if (body != null) {
        return RequestBody.create(HttpConsts.MEDIA_TYPE_OCTET_STREAM, body);
    }
    RequestBody requestBody;
    if (hasParts()) {
        final MultipartBuilder multipart = new MultipartBuilder();
        for (final BodyPart part : parts()) {
            if (part.getBody() != null) {
                multipart.addFormDataPart(part.getName(), part.getFileName(), part.getBody());
            }
        }
        for (Map.Entry<String, String> entry : form().entrySet()) {
            final String key = entry.getKey();
            final String value = entry.getValue();
            multipart.addFormDataPart(key, value == null ? "" : value);
        }
        requestBody = multipart.type(MultipartBuilder.FORM).build();
    } else if (hasForms()) {
        final FormEncodingBuilder bodyBuilder = new FormEncodingBuilder();
        for (Map.Entry<String, String> entry : form().entrySet()) {
            final String key = entry.getKey();
            final String value = entry.getValue();
            bodyBuilder.add(key, value == null ? "" : value);
        }
        requestBody = bodyBuilder.build();
    } else {
        requestBody = null;
    }
    return requestBody;
}

From source file:com.onaio.steps.helper.UploadFileTask.java

License:Apache License

@Override
protected Boolean doInBackground(File... files) {
    if (!TextUtils.isEmpty(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL))) {
        try {/*  w w  w  .  j a va 2s  .c o  m*/
            OkHttpClient client = new OkHttpClient();

            final MediaType MEDIA_TYPE = MediaType.parse("text/csv");

            RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                    .addFormDataPart("file", files[0].getName(), RequestBody.create(MEDIA_TYPE, files[0]))
                    .build();

            Request request = new Request.Builder()
                    .url(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL)).post(requestBody)
                    .build();
            client.newCall(request).execute();
            new CustomNotification().notify(activity, R.string.export_complete,
                    R.string.export_complete_message);
            return true;
        } catch (IOException e) {
            new Logger().log(e, "Export failed.");
            new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed);
        }
    } else {
        new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed);
    }

    return false;
}

From source file:com.secupwn.aimsicd.utils.RequestTask.java

@Override
protected String doInBackground(String... commandString) {

    // We need to create a separate case for UPLOADING to DBe (OCID, MLS etc)
    switch (mType) {
    // OCID upload request from "APPLICATION" drawer title
    case DBE_UPLOAD_REQUEST:
        try {/*  w w w.j  a  va 2  s  .  c  om*/
            @Cleanup
            Realm realm = Realm.getDefaultInstance();
            boolean prepared = mDbAdapter.prepareOpenCellUploadData(realm);

            log.info("OCID upload data prepared - " + String.valueOf(prepared));
            if (prepared) {
                File file = new File((mAppContext.getExternalFilesDir(null) + File.separator)
                        + "OpenCellID/aimsicd-ocid-data.csv");
                publishProgress(25, 100);

                RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                        .addFormDataPart("key", CellTracker.OCID_API_KEY).addFormDataPart("datafile",
                                "aimsicd-ocid-data.csv", RequestBody.create(MediaType.parse("text/csv"), file))
                        .build();

                Request request = new Request.Builder().url("http://www.opencellid.org/measure/uploadCsv")
                        .post(requestBody).build();

                publishProgress(60, 100);

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

                publishProgress(80, 100);
                if (response != null) {
                    log.info("OCID Upload Response: " + response.code() + " - " + response.message());
                    if (response.code() == 200) {
                        Realm.Transaction transaction = mDbAdapter.ocidProcessed();
                        realm.executeTransaction(transaction);
                    }
                    publishProgress(95, 100);
                }
                return "Successful";
            } else {
                Helpers.msgLong(mAppContext, mAppContext.getString(R.string.no_data_for_publishing));
                return null;
            }

            // all caused by httpclient.execute(httppost);
        } catch (UnsupportedEncodingException e) {
            log.error("Upload OpenCellID data Exception", e);
        } catch (FileNotFoundException e) {
            log.error("Upload OpenCellID data Exception", e);
        } catch (IOException e) {
            log.error("Upload OpenCellID data Exception", e);
        } catch (Exception e) {
            log.error("Upload OpenCellID data Exception", e);
        }

        // DOWNLOADING...
    case DBE_DOWNLOAD_REQUEST: // OCID download request from "APPLICATION" drawer title
        mTimeOut = REQUEST_TIMEOUT_MENU;
    case DBE_DOWNLOAD_REQUEST_FROM_MAP: // OCID download request from "Antenna Map Viewer"
        int count;
        try {
            long total;
            int progress = 0;
            String dirName = getOCDBDownloadDirectoryPath(mAppContext);
            File dir = new File(dirName);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, OCDB_File_Name);
            log.info("DBE_DOWNLOAD_REQUEST write to: " + dirName + OCDB_File_Name);

            Request request = new Request.Builder().url(commandString[0]).get().build();

            Response response;
            try {
                // OCID's API can be slow. Give it up to a minute to do its job. Since this
                // is a backgrounded task, it's ok to wait for a while.
                okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
                response = okHttpClient.newCall(request).execute();
                okHttpClient.setReadTimeout(10, TimeUnit.SECONDS); // Restore back to default
            } catch (SocketTimeoutException e) {
                log.warn("Trying to talk to OCID timed out after 60 seconds. API is slammed? Throttled?");
                return "Timeout";
            }

            if (response.code() != 200) {
                try {
                    String error = response.body().string();
                    Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + error);
                    log.error("Download OCID data error: " + error);
                } catch (Exception e) {
                    Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " "
                            + e.getClass().getName() + " - " + e.getMessage());
                    log.error("Download OCID exception: ", e);
                }
                return "Error";
            } else {
                // This returns "-1" for streamed response (Chunked Transfer Encoding)
                total = response.body().contentLength();
                if (total == -1) {
                    log.debug("doInBackground DBE_DOWNLOAD_REQUEST total not returned!");
                    total = 1024; // Let's set it arbitrarily to something other than "-1"
                } else {
                    log.debug("doInBackground DBE_DOWNLOAD_REQUEST total: " + total);
                    publishProgress((int) (0.25 * total), (int) total); // Let's show something!
                }

                FileOutputStream output = new FileOutputStream(file, false);
                InputStream input = new BufferedInputStream(response.body().byteStream());

                byte[] data = new byte[1024];
                while ((count = input.read(data)) > 0) {
                    // writing data to file
                    output.write(data, 0, count);
                    progress += count;
                    publishProgress(progress, (int) total);
                }
                input.close();
                // flushing output
                output.flush();
                output.close();
            }
            return "Successful";

        } catch (IOException e) {
            log.warn("Problem reading data from steam", e);
            return null;
        }
    }

    return null;
}

From source file:com.td.innovate.app.Activity.CaptureActivity.java

Call postImage(Callback callback) throws Throwable {
    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
            .addPart(Headers.of("Content-Disposition", "form-data; name=\"image_request[locale]\""),
                    RequestBody.create(null, "en-US"))
            .addPart(/* ww w .j  ava  2s.  c o m*/
                    Headers.of("Content-Disposition",
                            "form-data; name=\"image_request[image]\"; filename=\"testimage.jpg\""),
                    RequestBody.create(MEDIA_TYPE_JPG, new File(fileUri.getPath())))
            .build();

    Request request = new Request.Builder().header("Authorization", "CloudSight " + CLOUDSIGHT_KEY).url(reqUrl)
            .post(requestBody).build();

    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}

From source file:com.wialon.remote.OkSdkHttpClient.java

License:Apache License

@Override
public void postFile(String url, Map<String, String> params, Callback callback, int timeout, File file) {
    //Method will work at 2.1 version of library https://github.com/square/okhttp/issues/963 and https://github.com/square/okhttp/pull/969
    MultipartBuilder builder = new MultipartBuilder();
    builder.type(MultipartBuilder.FORM);
    RequestBody paramsBody = paramsMapToRequestBody(params);
    if (paramsBody != null) {
        builder.addPart(paramsBody);/*from w w w  .java 2  s  .co m*/
    }
    builder.addPart(RequestBody.create(MediaType.parse(""), file));
    Request request = new Request.Builder().url(url).post(builder.build()).build();
    threadPool.submit(new HttpRequest(getHttpClient(timeout), request, callback));
}

From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java

License:Open Source License

@Override
public void uploadTestRun(String testSpecificationId, FilePath workspace, String includes, String excludes,
        Map<String, Object> metadata, PrintStream logger) throws IOException, InterruptedException {
    if (testSpecificationId == null || testSpecificationId.isEmpty()) {
        throw new IllegalArgumentException(
                "No test specification id specified. Does the test specification still exist in XL TestView?");
    }//  ww w  .  java2s  .  c om
    try {
        logInfo(logger,
                format("Collecting files from '%s' using include pattern: '%s' and exclude pattern '%s'",
                        workspace.getRemote(), includes, excludes));

        DirScanner scanner = new DirScanner.Glob(includes, excludes);

        ObjectMapper objectMapper = new ObjectMapper();

        RequestBody body = new MultipartBuilder().type(MultipartBuilder.MIXED)
                .addPart(RequestBody.create(MediaType.parse(APPLICATION_JSON_UTF_8),
                        objectMapper.writeValueAsString(metadata)))
                .addPart(new ZipRequestBody(workspace, scanner, logger)).build();

        Request request = new Request.Builder()
                .url(createSensibleURL(API_IMPORT + "/" + testSpecificationId, serverUrl))
                .header("User-Agent", getUserAgent()).header("Accept", APPLICATION_JSON_UTF_8)
                .header("Authorization", createCredentials()).header("Transfer-Encoding", "chunked").post(body)
                .build();

        Response response = client.newCall(request).execute();
        ObjectMapper mapper = createMapper();
        ImportError importError;
        switch (response.code()) {
        case 200:
            logInfo(logger, "Sent data successfully");
            return;
        case 304:
            logWarn(logger, "No new results were detected. Nothing was imported.");
            throw new IllegalStateException("No new results were detected. Nothing was imported.");
        case 400:
            importError = mapper.readValue(response.body().byteStream(), ImportError.class);
            throw new IllegalStateException(importError.getMessage());
        case 401:
            throw new AuthenticationException(String.format(
                    "User '%s' and the supplied password are unable to log in", credentials.getUsername()));
        case 402:
            throw new PaymentRequiredException("The XL TestView server does not have a valid license");
        case 404:
            throw new ConnectionException("Cannot find test specification '" + testSpecificationId
                    + ". Please check if the XL TestView server is "
                    + "running and the test specification exists.");
        case 422:
            logWarn(logger, "Unable to process results.");
            logWarn(logger,
                    "Are you sure your include/exclude pattern provides all needed files for the test tool?");
            importError = mapper.readValue(response.body().byteStream(), ImportError.class);
            throw new IllegalStateException(importError.getMessage());
        default:
            throw new IllegalStateException("Unknown error. Status code: " + response.code()
                    + ". Response message: " + response.toString());
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        e.printStackTrace();
        LOG.warn("I/O error uploading test run data to {} {}\n{}", serverUrl.toString(), e.toString(), e);
        throw new IOException(
                "I/O error uploading test run data to " + serverUrl.toString() + " " + e.toString(), e);
    }
}