List of usage examples for com.squareup.okhttp MultipartBuilder FORM
MediaType FORM
To view the source code for com.squareup.okhttp MultipartBuilder FORM.
Click Source Link
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())); }/*from ww w.j a v a 2s. c o 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();/*from w ww . j av a 2 s. com*/ 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//www . j a v a 2s . co 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 w w . ja v a 2s . com 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 {/*from w w w .j ava 2 s .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 av a2 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(/*w w w . jav a2 s.c om*/ 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 ww . j a v a 2s. c o 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:de.ebf.UploadFileOneSkyAppMojo.java
License:Apache License
private void uploadFiles() throws MojoExecutionException { try {/*w w w . java2 s . c o m*/ 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 www . j a v a 2 s . com*/ 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; }