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: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."); }/*w w w. j ava 2s . 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 a v a 2s. 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 {//w w w . jav a 2 s . com 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 w w. jav a 2s .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 w w w . j a v a2 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)); }/* w ww.j a v a 2 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 {//www. ja v a 2 s . com 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());//www . j ava2s . com 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./*w w w .jav 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:studio.imedia.vehicleinspection.activity.PersonalInfoActivity.java
/** * ?/* w w w. j av a 2 s .c om*/ * * @param urlSB */ private void uploadAvatar(StringBuffer urlSB, File avatarFile) { String url = urlSB.toString(); String filename = avatarFile.getName(); File file = avatarFile; String avatarPath = null; // TODO // RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file); RequestBody fileBody = RequestBody.create(Constant.Media.TYPE_JPEG, file); RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addPart(Headers.of("Content-Disposition", "form-data; name=\"uploadFile\""), fileBody).build(); Request request = new Request.Builder().url(url).post(requestBody).build(); mClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { mHandler.sendEmptyMessage(CONNECT_FAIL); } @Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } String jsonStr = response.body().string(); Log.d("files", jsonStr); try { int status = new JSONObject(jsonStr).getInt("status"); Log.d("files", "the status is " + status); } catch (JSONException e) { e.printStackTrace(); } } }); // TODO ?? // Message msg = new Message(); // msg.what = MSG_UPLOAD_AVATAR_SUCCESS; // msg.obj = avatarPath; // mHandler.sendMessage(msg); }