public String startOnline() throws IOException { String uri = address + "api/active/receiver/start"; LinkedList<FormBodyPart> partsList = new LinkedList<>(); partsList.add(new FormBodyPart("token", new StringBody(token))); partsList.add(new FormBodyPart("projectKey", new StringBody(project))); partsList.add(new FormBodyPart("title", new StringBody(title))); JSONObject obj = queryObject(createPost(uri, partsList), 201); return address + "gui/active/" + obj.optString("OnlineID", "N/A") + "/"; }
private static int postData(String url, byte[] encryptedBytes, byte[] encryptedSecretKey, byte[] signature, String serviceName) throws IOException { MultipartEntity multipartEntity = new MultipartEntity(); String filename=serviceName+'_'+System.currentTimeMillis()+".hl7"; multipartEntity.addPart("importFile", new ByteArrayBody(encryptedBytes, filename)); multipartEntity.addPart("key", new StringBody(new String(Base64.encodeBase64(encryptedSecretKey), MiscUtils.DEFAULT_UTF8_ENCODING))); multipartEntity.addPart("signature", new StringBody(new String(Base64.encodeBase64(signature), MiscUtils.DEFAULT_UTF8_ENCODING))); multipartEntity.addPart("service", new StringBody(serviceName)); multipartEntity.addPart("use_http_response_code", new StringBody("true")); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(multipartEntity); HttpClient httpClient = getTrustAllHttpClient(); httpClient.getParams().setParameter("http.connection.timeout", CONNECTION_TIME_OUT); HttpResponse httpResponse = httpClient.execute(httpPost); int statusCode=httpResponse.getStatusLine().getStatusCode(); logger.debug("StatusCode:" + statusCode); return (statusCode); }
private HttpPost composeMultiPartFormRequest(final String uri, final Parameters parameters, final Map<String, ContentBody> files) { HttpPost request = new HttpPost(uri); MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { Charset utf8 = Charset.forName("UTF-8"); for(Parameter param : parameters) if(param.isSingleValue()) multiPartEntity.addPart(param.getName(), new StringBody(param.getValue(), utf8)); else for(String value : param.getValues()) multiPartEntity.addPart(param.getName(), new StringBody(value, utf8)); } catch (UnsupportedEncodingException e) { throw MechanizeExceptionFactory.newException(e); } List<String> fileNames = new ArrayList<String>(files.keySet()); Collections.sort(fileNames); for(String name : fileNames) { ContentBody contentBody = files.get(name); multiPartEntity.addPart(name, contentBody); } request.setEntity(multiPartEntity); return request; }
private static FormBodyPart newFileBody(final String parameterName, final String fileName, final String fileContent) throws Exception { return new FormBodyPart( parameterName, new StringBody(fileContent, ContentType.TEXT_PLAIN) { @Override public String getFilename() { return fileName; } @Override public String getTransferEncoding() { return "binary"; } @Override public String getMimeType() { return ""; } @Override public String getCharset() { return null; } }); }
public HttpPost initRequest(final FileUploadParameter parameter) { final FileUploadAddress fileUploadAddress = getDependResult(FileUploadAddress.class); final HttpPost request = new HttpPost("http://" + fileUploadAddress.getData().getUp() + CONST.URI_PATH); final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setCharset(Consts.UTF_8); multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart(CONST.QID_NAME, new StringBody(getLoginInfo().getQid(), ContentType.DEFAULT_BINARY)); multipartEntity.addPart("ofmt", new StringBody("json", ContentType.DEFAULT_BINARY)); multipartEntity.addPart("method", new StringBody("Upload.web", ContentType.DEFAULT_BINARY)); multipartEntity.addPart("token", new StringBody(readCookieStoreValue("token"), ContentType.DEFAULT_BINARY)); multipartEntity.addPart("v", new StringBody("1.0.1", ContentType.DEFAULT_BINARY)); multipartEntity.addPart("tk", new StringBody(fileUploadAddress.getData().getTk(), ContentType.DEFAULT_BINARY)); multipartEntity.addPart("Upload", new StringBody("Submit Query", ContentType.DEFAULT_BINARY)); multipartEntity.addPart("devtype", new StringBody("web", ContentType.DEFAULT_BINARY)); multipartEntity.addPart("pid", new StringBody("ajax", ContentType.DEFAULT_BINARY)); multipartEntity.addPart("Filename", new StringBody(parameter.getUploadFile().getName(), ContentType.APPLICATION_JSON)); multipartEntity.addPart("path", new StringBody(parameter.getPath(), ContentType.APPLICATION_JSON));// 解决中文不识别问题 multipartEntity.addBinaryBody("file", parameter.getUploadFile()); request.setEntity(multipartEntity.build()); return request; }
private void uploadDatabase() throws Exception { tempDB = File.createTempFile("temp_", ".sqlite", serviceModule.getDirectoryPath()); databaseManager.mergeRecord().dumpDatabaseTo(tempDB); // check if database is empty if (databaseManager.mergeRecord().isEmpty(tempDB)) { FLog.d("database is empty"); return; } HashMap<String, ContentBody> extraParts = new HashMap<String, ContentBody>(); extraParts.put("user", new StringBody(databaseManager.getUserId())); if (!uploadFile("db", Request.DATABASE_UPLOAD_REQUEST(serviceModule), tempDB, serviceModule.getDirectoryPath(), extraParts)) { FLog.d("Failed to upload database"); return; } }
public VerificationItems postForm(final Map<String, String> formParamValueMap, final String endpoint, final String boundary){ final HttpPost httpPost = new HttpPost(endpoint); httpPost.setHeader(MultipartController.VERIFICATION_CONTROL_HEADER_NAME, MultipartController.VERIFICATION_CONTROL_FORM); try { for (Map.Entry<String, String> param : formParamValueMap.entrySet()) { HttpEntity httpEntity = MultipartEntityBuilder .create() .setBoundary(boundary) .setContentType(ContentType.MULTIPART_FORM_DATA) //.addPart(FormBodyPartBuilder.create().addField(param.getKey(), param.getValue()).build()) .addPart(param.getKey(), new StringBody(param.getValue())) .build(); httpPost.setEntity(httpEntity); } }catch (Exception e){ throw new IllegalStateException("Error preparing the post request", e); } return post(httpPost); }
@Test public void testStringBody() throws Exception { final StringBody b1 = new StringBody("text", ContentType.DEFAULT_TEXT); Assert.assertEquals(4, b1.getContentLength()); Assert.assertEquals("ISO-8859-1", b1.getCharset()); Assert.assertNull(b1.getFilename()); Assert.assertEquals("text/plain", b1.getMimeType()); Assert.assertEquals("text", b1.getMediaType()); Assert.assertEquals("plain", b1.getSubType()); Assert.assertEquals(MIME.ENC_8BIT, b1.getTransferEncoding()); final StringBody b2 = new StringBody("more text", ContentType.create("text/other", MIME.DEFAULT_CHARSET)); Assert.assertEquals(9, b2.getContentLength()); Assert.assertEquals(MIME.DEFAULT_CHARSET.name(), b2.getCharset()); Assert.assertNull(b2.getFilename()); Assert.assertEquals("text/other", b2.getMimeType()); Assert.assertEquals("text", b2.getMediaType()); Assert.assertEquals("other", b2.getSubType()); Assert.assertEquals(MIME.ENC_8BIT, b2.getTransferEncoding()); }
@Test public void testBuildBodyPartBasics() throws Exception { final StringBody stringBody = new StringBody("stuff", ContentType.TEXT_PLAIN); final FormBodyPart bodyPart = FormBodyPartBuilder.create() .setName("blah") .setBody(stringBody) .build(); Assert.assertNotNull(bodyPart); Assert.assertEquals("blah", bodyPart.getName()); Assert.assertEquals(stringBody, bodyPart.getBody()); final Header header = bodyPart.getHeader(); Assert.assertNotNull(header); assertFields(Arrays.asList( new MinimalField("Content-Disposition", "form-data; name=\"blah\""), new MinimalField("Content-Type", "text/plain; charset=ISO-8859-1"), new MinimalField("Content-Transfer-Encoding", "8bit")), header.getFields()); }
public static MultipartEntity encodePOSTUrl(MultipartEntity mEntity, Bundle parameters) { if (parameters != null && parameters.size() > 0) { boolean first = true; for (String key : parameters.keySet()) { if (key != null) { if (first) { first = false; } String value = ""; Object object = parameters.get(key); if (object != null) { value = String.valueOf(object); } try { mEntity.addPart(key, new StringBody(value)); } catch (Exception e) { e.printStackTrace(); } } } } return mEntity; }
public void editWikiPage(String[][] currentCommentInformation, String subreddit) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://www.reddit.com/r/"+subreddit+"/api/wiki/edit"); MultipartEntity nvps = new MultipartEntity(); httpPost.addHeader("User-Agent","User-Agent: LGG Bot (by /u/amdphenom"); httpPost.addHeader("Cookie","reddit_session=" + user.getCookie()); nvps.addPart("r", new StringBody(subreddit)); nvps.addPart("uh", new StringBody(user.getModhash())); nvps.addPart("formid", new StringBody("image-upload")); httpPost.setEntity(nvps); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); } finally { response2.close(); } }
private void fileUpload() throws Exception { httpPost = new NUHttpPost(postURL); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("notprivate", new StringBody("false")); mpEntity.addPart("folder", new StringBody("/")); mpEntity.addPart("Filedata", createMonitoredFileBody()); httpPost.setHeader("Cookie", usercookie); httpPost.setEntity(mpEntity); uploading(); NULogger.getLogger().info("Now uploading your file into zippyshare.com"); httpResponse = httpclient.execute(httpPost); gettingLink(); HttpEntity resEntity = httpResponse.getEntity(); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); downloadlink = StringUtils.stringBetweenTwoStrings(uploadresponse, "value=\"http://", "\""); downloadlink = "http://" + downloadlink; NULogger.getLogger().log(Level.INFO, "Download Link : {0}", downloadlink); downURL=downloadlink; }else{ throw new Exception("ZippyShare server problem or Internet connectivity problem"); } }
/** * Upload with <a href="http://www.sockshare.com/apidocs.php">API</a>. */ private void apiUpload() throws UnsupportedEncodingException, IOException, Exception{ uploading(); ContentBody cbFile = createMonitoredFileBody(); NUHttpPost httppost = new NUHttpPost(apiURL); MultipartEntity mpEntity = new MultipartEntity(); mpEntity.addPart("file", cbFile); mpEntity.addPart("user", new StringBody(sockShareAccount.username)); mpEntity.addPart("password", new StringBody(sockShareAccount.password)); httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); String reqResponse = EntityUtils.toString(response.getEntity()); //NULogger.getLogger().info(reqResponse); if(reqResponse.contains("File Uploaded Successfully")){ gettingLink(); downURL = StringUtils.stringBetweenTwoStrings(reqResponse, "<link>", "</link>"); } else{ //Handle the errors status = UploadStatus.GETTINGERRORS; throw new Exception(StringUtils.stringBetweenTwoStrings(reqResponse, "<message>", "</message>")); } }
private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); file = new File("h:/install.txt"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into sharesend.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } System.out.println("Upload Response : " + uploadresponse); System.out.println("Download Link : http://sharesend.com/" + uploadresponse); httpclient.getConnectionManager().shutdown(); }
/** * Submit an application bundle to execute as a job. */ protected JsonObject postJob(CloseableHttpClient httpClient, JsonObject service, File bundle, JsonObject jobConfigOverlay) throws IOException { String url = getJobSubmitUrl(httpClient, bundle); HttpPost postJobWithConfig = new HttpPost(url); postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAuthorization()); FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM); StringBody configBody = new StringBody(jobConfigOverlay.toString(), ContentType.APPLICATION_JSON); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("sab", bundleBody) .addPart(DeployKeys.JOB_CONFIG_OVERLAYS, configBody).build(); postJobWithConfig.setEntity(reqEntity); JsonObject jsonResponse = StreamsRestUtils.getGsonResponse(httpClient, postJobWithConfig); RemoteContext.REMOTE_LOGGER.info("Streaming Analytics service (" + getName() + "): submit job response:" + jsonResponse.toString()); return jsonResponse; }
private void uploadMixtureCloud() throws Exception { uploadInitialising(); responseString = NUHttpClientUtils.getData("https://www.mixturecloud.com/files", httpContext); uploadUrl = "http:" + StringUtils.stringBetweenTwoStrings(responseString, "urlUpload : '", "',"); NULogger.getLogger().log(Level.INFO, "uploadUrl is {0}", uploadUrl); httpPost = new NUHttpPost(uploadUrl); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("cmd", new StringBody("upload")); mpEntity.addPart("target", new StringBody("mcm1_MA")); mpEntity.addPart("upload[]", createMonitoredFileBody()); httpPost.setEntity(mpEntity); uploading(); httpResponse = httpclient.execute(httpPost, httpContext); HttpEntity resEntity = httpResponse.getEntity(); responseString = EntityUtils.toString(resEntity); //NULogger.getLogger().log(Level.INFO, "stringResponse : {0}", responseString); JSONObject jSonObject = new JSONObject(responseString); String webAccess = jSonObject.getJSONArray("file_data").getJSONObject(0).getString("web_access"); downloadUrl += webAccess; downURL = downloadUrl; }
public void sendOnlineData(JSONArray data) throws IOException { String uri = address + "api/active/receiver/data"; LinkedList<FormBodyPart> partsList = new LinkedList<>(); String dataStr = data.toString(); log.debug("Sending active test data: " + dataStr); partsList.add(new FormBodyPart("data", new StringBody(dataStr))); query(createPost(uri, partsList), 202); }
private LinkedList<FormBodyPart> getUploadParts(File targetFile, LinkedList<String> perfMonFiles) throws IOException { if (targetFile.length() == 0) { throw new IOException("Cannot send empty file to BM.Sense"); } log.info("Preparing files to send"); LinkedList<FormBodyPart> partsList = new LinkedList<>(); partsList.add(new FormBodyPart("projectKey", new StringBody(project))); partsList.add(new FormBodyPart("jtl_file", new FileBody(gzipFile(targetFile)))); Iterator<String> it = perfMonFiles.iterator(); int index = 0; while (it.hasNext()) { File perfmonFile = new File(it.next()); if (!perfmonFile.exists()) { log.warn("File not exists, skipped: " + perfmonFile.getAbsolutePath()); continue; } if (perfmonFile.length() == 0) { log.warn("Empty file skipped: " + perfmonFile.getAbsolutePath()); continue; } partsList.add(new FormBodyPart("perfmon_" + index, new FileBody(gzipFile(perfmonFile)))); index++; } return partsList; }
@SuppressWarnings("unchecked") private HttpEntity createFileEntity(Object files) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String, Object> entry : ((Map<String, Object>) files).entrySet()) { if (new File(entry.getValue().toString()).exists()) { builder.addPart(entry.getKey(), new FileBody(new File(entry.getValue().toString()), ContentType.DEFAULT_BINARY)); } else { builder.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), ContentType.DEFAULT_TEXT)); } } return builder.build(); }
ContentBody constructContentBody() throws UnsupportedEncodingException { ContentType contentTypeObject = constructContentTypeObject(); if (filePath != null) { // FILE part if (contentTypeObject != null) { return new FileBody(new File(filePath), contentTypeObject); } else { return new FileBody(new File(filePath)); } } else if (content != null) { // TEXT part if (contentTypeObject != null) { return new StringBody(content, contentTypeObject); } else { return new StringBody(content, ContentType.TEXT_PLAIN); } } else { // BYTE ARRAY part if (contentTypeObject != null) { return new ByteArrayBody(this.fileBytes, contentTypeObject, fileName); } else { return new ByteArrayBody(this.fileBytes, fileName); } } }
/** * Retorna a lista de anexos de uma transação com ou sem filtro de tipo * @param idTransacao: Código da transação à ser consultada * @param arquivo: Arquivo à ser anexado (imagem [JPEG/PNG] ou documento [PDF]) * @param tipoAnexo: Tipo de anexo à ser enviado * @return boolean */ public boolean attachFileToTransaction(String idTransacao, File arquivo, TipoAnexo tipoAnexo) throws IOException, PJBankException { Set<String> extensoesPermitidas = new HashSet<>(); extensoesPermitidas.add("pdf"); extensoesPermitidas.add("jpg"); extensoesPermitidas.add("jpeg"); extensoesPermitidas.add("png"); if (!extensoesPermitidas.contains(FilenameUtils.getExtension(arquivo.getName()))) { throw new IllegalArgumentException("O arquivo a ser anexado em uma transação deve estar no formato PDF, JPG," + " JPEG ou PNG, sendo assim um documento ou uma imagem."); } PJBankClient client = new PJBankClient(this.endPoint.concat("/transacoes/").concat(idTransacao).concat("/documentos")); HttpPost httpPost = client.getHttpPostClient(); httpPost.addHeader("x-chave-conta", this.chave); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); //FileBody fileBody = new FileBody(arquivo); StringBody stringBody = new StringBody(tipoAnexo.getName(), ContentType.TEXT_PLAIN); //builder.addPart("arquivos", fileBody); builder.addBinaryBody("arquivos", arquivo, ContentType.APPLICATION_OCTET_STREAM, arquivo.getName()); builder.addPart("tipo", stringBody); httpPost.setEntity(builder.build()); return client.doRequest(httpPost).getStatusLine().getStatusCode() == 201; }
public boolean cmdLogUploadSync(final String cmdId, final Path path) { if (!Config.isUploadLog()) { LOGGER.trace("Log upload toggle is disabled"); return true; } HttpEntity entity = MultipartEntityBuilder.create() .addPart("file", new FileBody(path.toFile(), ContentType.create("application/zip"))) .addPart("cmdId", new StringBody(cmdId, ContentType.create("text/plain", Charsets.UTF_8))) .setContentType(ContentType.MULTIPART_FORM_DATA) .build(); String url = Config.agentSettings().getCmdLogUrl(); HttpResponse<String> response = HttpClient.build(url) .post(entity) .retry(5) .bodyAsString(); if (!response.hasSuccess()) { LOGGER.warn("Fail to upload zipped cmd log to : %s ", url); return false; } LOGGER.trace("Zipped cmd log uploaded %s", path); return true; }
@Override public String uploadFile(String systemName, String entityName, String apiUrl, List<File> fileList, String requestParamInputName) throws IllegalStateException { HttpResponse response = null; HttpPost httpPost = getHttpPost(); try { List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>(); String[] urlAndParame = apiUrl.split("\\?"); String apiUrlNoParame = urlAndParame[0]; Map<String, String> parameMap = StrUtil.splitUrlToParameMap(apiUrl); Iterator<String> parameIterator = parameMap.keySet().iterator(); httpPost.setURI(new URI(apiUrlNoParame)); MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); while (parameIterator.hasNext()) { String parameName = parameIterator.next(); nvps.add(new BasicNameValuePair(parameName, parameMap.get(parameName))); multipartEntity.addPart(parameName, new StringBody(parameMap.get(parameName), ContentType.create("text/plain", Consts.UTF_8))); } if (!StrUtil.isBlank(systemName)) { multipartEntity.addPart("systemName", new StringBody(systemName, ContentType.create("text/plain", Consts.UTF_8))); } if (!StrUtil.isBlank(entityName)) { multipartEntity.addPart("entityName", new StringBody(entityName, ContentType.create("text/plain", Consts.UTF_8))); } // 多文件上传 获取文件数组前台标签name值 if (!StrUtil.isBlank(requestParamInputName)) { multipartEntity.addPart("filesName", new StringBody(requestParamInputName, ContentType.create("text/plain", Consts.UTF_8))); } if (fileList != null) { for (int i = 0, size = fileList.size(); i < size; i++) { File file = fileList.get(i); multipartEntity.addBinaryBody(requestParamInputName, file, ContentType.DEFAULT_BINARY, file.getName()); } } HttpEntity entity = multipartEntity.build(); httpPost.setEntity(entity); response = httpClient.execute(httpPost); String statusCode = String.valueOf(response.getStatusLine().getStatusCode()); if (statusCode.indexOf("20") == 0) { entity = response.getEntity(); // String contentType = entity.getContentType().getValue();// // application/json;charset=ISO-8859-1 return StrUtil.readStream(entity.getContent(), responseContextEncode); } else { LOG.error("返回状态码:[" + statusCode + "]"); return "返回状态码:[" + statusCode + "]"; } } catch (Exception e) { e.printStackTrace(); } finally { httpPost.releaseConnection(); } return null; }
public ApiResponse uploadWelcomeMessage(String filePath, int messageId, int selectedMessageId) { File file = new File(filePath); HttpPost uploadRequest = new HttpPost(WELCOME_MESSAGE_URI); StringBody commandeBody = new StringBody("annonce_mess", ContentType.MULTIPART_FORM_DATA); StringBody messageIdBody = new StringBody(String.valueOf(messageId), ContentType.MULTIPART_FORM_DATA); StringBody maxFileSizeBody = new StringBody("5242880", ContentType.MULTIPART_FORM_DATA); StringBody selectMessageBody = new StringBody(String.valueOf(selectedMessageId), ContentType.MULTIPART_FORM_DATA); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("FILE", file, ContentType.create("audio/mp3"), "message.mp3"); builder.addPart("commande", commandeBody); builder.addPart("id_message", messageIdBody); builder.addPart("id_message_select", selectMessageBody); builder.addPart("MAX_FILE_SIZE", maxFileSizeBody); HttpEntity entity = builder.build(); uploadRequest.setEntity(entity); HttpResponse response = executeRequest(uploadRequest); return new ApiResponse(HttpStatus.gethttpStatus(response.getStatusLine().getStatusCode())); }
private void addString(String id, String str) { try { multiPart.addPart(id, new StringBody(str, Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
private HttpPost buildHttpPost(String fileNameWithPath, String product) { HttpPost httpPost = new HttpPost(LogUtil.getInstance().getLogUrl()); MultipartEntity mutiEntity = new MultipartEntity(HttpMultipartMode.STRICT); httpPost.setEntity(mutiEntity); File file = new File(fileNameWithPath); try { mutiEntity.addPart("LogFileInfo", new StringBody("{\"product\":\"" + product + "\"}", Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "UTF-8 is not supported encode"); //LOGGER.error("UTF-8 is not supported encode"); } mutiEntity.addPart("LogFile", new FileBody(file)); return httpPost; }
private String sendFile(String chat_id, File file, String type, String caption, boolean disable_notification, int reply_to_message_id, ReplyMarkup reply_markup, int duration, String performer, String title, int width, int height) throws IOException { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("chat_id", new StringBody(chat_id, ContentType.DEFAULT_TEXT)); if (caption != null) builder.addPart("caption", new StringBody(caption, ContentType.DEFAULT_TEXT)); if (disable_notification != false) builder.addPart("disable_notification", new StringBody(Boolean.toString(disable_notification), ContentType.DEFAULT_TEXT)); if (reply_to_message_id > 0) builder.addPart("reply_to_message_id", new StringBody(Integer.toString(reply_to_message_id), ContentType.DEFAULT_TEXT)); if (reply_markup != null) builder.addPart("reply_markup", new StringBody(URLEncoder.encode(reply_markup.toJSONString(), "utf-8"), ContentType.DEFAULT_TEXT)); if (duration > 0) builder.addPart("duration", new StringBody(Integer.toString(duration), ContentType.DEFAULT_TEXT)); if (performer != null) builder.addPart("performer", new StringBody(performer, ContentType.DEFAULT_TEXT)); if (title != null) builder.addPart("title", new StringBody(title, ContentType.DEFAULT_TEXT)); if (width > 0) builder.addPart("width", new StringBody(Integer.toString(width), ContentType.DEFAULT_TEXT)); if (height > 0) builder.addPart("height", new StringBody(Integer.toString(height), ContentType.DEFAULT_TEXT)); builder.addPart(type, new FileBody(file, ContentType.DEFAULT_BINARY)); HttpEntity entity = builder.build(); HttpPost post = new HttpPost(url + "/send" + type); post.setEntity(entity); CloseableHttpClient httpclient = HttpClients.createMinimal(); HttpResponse response = httpclient.execute(post); return response.toString(); }
private String sendFile(String chat_id, String file_id, String type, String caption, boolean disable_notification, int reply_to_message_id, ReplyMarkup reply_markup, int duration, String performer, String title, int width, int height) throws IOException { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("chat_id", new StringBody(chat_id, ContentType.DEFAULT_TEXT)); if (caption != null) builder.addPart("caption", new StringBody(caption, ContentType.DEFAULT_TEXT)); if (disable_notification != false) builder.addPart("disable_notification", new StringBody(Boolean.toString(disable_notification), ContentType.DEFAULT_TEXT)); if (reply_to_message_id > 0) builder.addPart("reply_to_message_id", new StringBody(Integer.toString(reply_to_message_id), ContentType.DEFAULT_TEXT)); if (reply_markup != null) builder.addPart("reply_markup", new StringBody(URLEncoder.encode(reply_markup.toJSONString(), "utf-8"), ContentType.DEFAULT_TEXT)); if (duration > 0) builder.addPart("duration", new StringBody(Integer.toString(duration), ContentType.DEFAULT_TEXT)); if (performer != null) builder.addPart("performer", new StringBody(performer, ContentType.DEFAULT_TEXT)); if (title != null) builder.addPart("title", new StringBody(title, ContentType.DEFAULT_TEXT)); if (width > 0) builder.addPart("width", new StringBody(Integer.toString(width), ContentType.DEFAULT_TEXT)); if (height > 0) builder.addPart("height", new StringBody(Integer.toString(height), ContentType.DEFAULT_TEXT)); builder.addPart(type, new StringBody(file_id, ContentType.DEFAULT_TEXT)); HttpEntity entity = builder.build(); HttpPost post = new HttpPost(url + "/send" + type); post.setEntity(entity); CloseableHttpClient httpclient = HttpClients.createMinimal(); HttpResponse response = httpclient.execute(post); return response.toString(); }
private ContentBody newContentBody(Part part) { ContentType contentType = ContentType.create(part.getMediaType()); if (part instanceof TextPart) { TextPart textPart = (TextPart)part; return new StringBody(textPart.getText(), contentType); } BinaryPart binaryPart = (BinaryPart)part; return new InputStreamBody(binaryPart.getData(), contentType, binaryPart.getDownloadName()); }
@Test public void upload() throws IOException { String charset = "UTF-8"; HttpClient client = HttpClientBuilder.create().build(); String act = "upload"; HttpPost post = new HttpPost(getUploadUrl(act)); Map<String, Object> json = new HashMap<>(); json.put("name", "张三"); json.put("age", 23); String req = Base64.encodeBase64String(GsonUtil.toJson(json).getBytes(charset)); System.out.println("req:" + req); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("Api", StringBody.create("common", "text/plain", Charset.forName(charset))); reqEntity.addPart("data", StringBody.create(req, "text/plain", Charset.forName(charset))); reqEntity.addPart("img", new FileBody(new File("E:\\doc\\logo.jpg"))); post.setEntity(reqEntity); HttpResponse resp = client.execute(post); String line = resp.getStatusLine().toString(); Assert.assertEquals("HTTP/1.1 200 OK", line); HttpEntity resEntity = resp.getEntity(); Log.get("upload").info(EntityUtils.toString(resEntity, charset)); }
public String importImage(File file) throws IOException { if(getGalleryId() != null) { String url = getImportImageUrl(); HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get, context); this.cookies = response.getFirstHeader(Constant.SET_COOKIE_HEADER).getValue(); // load file in form FileBody cbFile = new FileBody(file); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("physical", cbFile); builder.addPart("title", new StringBody("Image importée via ZestWriter", Charset.forName("UTF-8"))); builder.addPart(Constant.CSRF_ZDS_KEY, new StringBody(getCookieValue(cookieStore, Constant.CSRF_COOKIE_KEY), ContentType.MULTIPART_FORM_DATA)); Pair<Integer, String> resultPost = sendPost(url, builder.build()); Document doc = Jsoup.parse(resultPost.getValue()); Elements endPoints = doc.select("input[name=avatar_url]"); if(!endPoints.isEmpty()) { return getBaseUrl() + endPoints.first().attr("value").trim(); } } return "http://"; }
private boolean uploadContent(String filePath, String url, String msg) throws IOException{ HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get, context); this.cookies = response.getFirstHeader(Constant.SET_COOKIE_HEADER).getValue(); // load file in form FileBody cbFile = new FileBody(new File(filePath)); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("archive", cbFile); builder.addPart("subcategory", new StringBody("115", ContentType.MULTIPART_FORM_DATA)); builder.addPart("msg_commit", new StringBody(msg, Charset.forName("UTF-8"))); builder.addPart(Constant.CSRF_ZDS_KEY, new StringBody(getCookieValue(cookieStore, Constant.CSRF_COOKIE_KEY), ContentType.MULTIPART_FORM_DATA)); Pair<Integer, String> resultPost = sendPost(url, builder.build()); int statusCode = resultPost.getKey(); switch (statusCode) { case 200: return !resultPost.getValue ().contains ("alert-box alert"); case 404: log.debug("L'id cible du contenu ou le slug est incorrect. Donnez de meilleur informations"); return false; case 403: log.debug("Vous n'êtes pas autorisé à uploader ce contenu. Vérifiez que vous êtes connecté"); return false; case 413: log.debug("Le fichier que vous essayer d'envoyer est beaucoup trop lourd. Le serveur n'arrive pas à le supporter"); return false; default: log.debug("Problème d'upload du contenu. Le code http de retour est le suivant : "+statusCode); return false; } }
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } if (resEntity != null) { resEntity.consumeContent(); } }
public WebResponse uploadFile(String path, String fname, InputStream in, String stoken) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(path); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); StringBody fn = new StringBody(fname, ContentType.MULTIPART_FORM_DATA); builder.addPart("fname", fn); builder.addBinaryBody("file", in, ContentType.APPLICATION_XML, fname); BasicCookieStore cookieStore = new BasicCookieStore(); if (stoken != null) { BasicClientCookie cookie = new BasicClientCookie( Constants.SECURE_TOKEN_NAME, stoken); cookie.setDomain(TestConstants.JETTY_HOST); cookie.setPath("/"); cookieStore.addCookie(cookie); } TestConstants.LOG.debug("stoken=" + stoken); HttpClient client = HttpClientBuilder.create(). setDefaultCookieStore(cookieStore).build(); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse response = client.execute(post); String body; ResponseHandler<String> handler = new BasicResponseHandler(); try { body = handler.handleResponse(response); } catch (HttpResponseException e) { return new WebResponse(e.getStatusCode(), e.getMessage()); } return new WebResponse(response.getStatusLine().getStatusCode(), body); }
@Override protected CloseableHttpResponse send(CloseableHttpClient httpClient, String baseUrl) throws Exception { //1)构建实体 MultipartEntityBuilder entBuilder = MultipartEntityBuilder.create(); for (String key : params.keySet()) { Object item = params.get(key); if(item instanceof File){ File file = (File)item; if((!file.exists()) || (file.isDirectory())){ throw new Exception("file error"); } entBuilder.addPart(key, new FileBody(file)); }else if(item instanceof String){ String value = (String)item; entBuilder.addPart(key, new StringBody(value, ContentType.TEXT_PLAIN)); }else{ throw new Exception(item.getClass().toString()+" not support"); } } HttpEntity reqEntity = entBuilder.build(); //2)发送并等待回复 HttpPost request = new HttpPost(baseUrl); request.setEntity(reqEntity); return httpClient.execute(request); }
private HttpPost buildHttpPost(String fileNameWithPath, String product) { HttpPost httpPost = new HttpPost(serverUrl); MultipartEntity mutiEntity = new MultipartEntity(HttpMultipartMode.STRICT); httpPost.setEntity(mutiEntity); File file = new File(fileNameWithPath); try { mutiEntity.addPart("LogFileInfo", new StringBody("{\"product\":\"" + product + "\"}", Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { logUtil.showRunningtLog(LOG_TYPE_E.LOG_ERROR, "LogFileUploadTask.buildHttpPost()", "UTF-8 is not supported encode"); } mutiEntity.addPart("LogFile", new FileBody(file)); return httpPost; }
/** * Do a http post with the multipart content type. This method is usually * used to upload the large size content, such as uploading a file. * * @param url * @param formParams * @param accessor * @return * @throws IOException * @throws YNoteException */ public static HttpResponse doPostByMultipart(String url, Map<String, Object> formParams, OAuthAccessor accessor) throws IOException, YNoteException { HttpPost post = new HttpPost(url); // for multipart encoded post, only sign with the oauth parameters // do not sign the our form parameters Header oauthHeader = getAuthorizationHeader(url, OAuthMessage.POST, null, accessor); if (formParams != null) { // encode our ynote parameters MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (Entry<String, Object> parameter : formParams.entrySet()) { if (parameter.getValue() instanceof File) { // deal with file particular entity.addPart(parameter.getKey(), new FileBody((File)parameter.getValue())); } else if (parameter.getValue() != null){ entity.addPart(parameter.getKey(), new StringBody( parameter.getValue().toString(), Charset.forName(YNoteConstants.ENCODING))); } } post.setEntity(entity); } post.addHeader(oauthHeader); HttpResponse response = client.execute(post); if ((response.getStatusLine().getStatusCode() / 100) != 2) { YNoteException e = wrapYNoteException(response); throw e; } return response; }
/** * 设置用户所在组织的形象设置 * * @param title * 软件标题 * @param windowsLogoFile * windows客户端显示的Logo,为null时代表清除Logo。 * @param androidLogoFile * android客户端显示的Logo,为null时代表清除Logo。 * @throws Exception */ public void setVi(String title, File windowsLogoFile, File androidLogoFile, String group) throws Exception { LOG.info("Update vi group of "+ group +" using title:"+title +",windowLogoPath:" + windowsLogoFile +",androidLogoPath:" + androidLogoFile); MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8")); if (title == null) { title = ""; } entity.addPart("clientTitle",new StringBody(title, Charset.forName("UTF-8"))); if (windowsLogoFile != null) { entity.addPart(LOGO_FOR_WINDOWS, new FileBody(windowsLogoFile)); } else { entity.addPart(LOGO_FOR_WINDOWS, new StringBody("")); } if (androidLogoFile != null) { entity.addPart(LOGO_FOR_ANDROID, new FileBody(androidLogoFile)); } else { entity.addPart(LOGO_FOR_ANDROID, new StringBody("")); } String url = getSetViUrl(group); postMultipartEntity(entity,url); }
/** * 设置用户所在组织所用的Android客户端软件的Logo * * @param androidLogoFile * 为null时代表清除Logo。 * @throws Exception */ public void setViAndroidLogo(File androidLogoFile,String group) throws Exception { MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8")); if (androidLogoFile != null) { entity.addPart(LOGO_FOR_ANDROID, new FileBody(androidLogoFile)); } else { entity.addPart(LOGO_FOR_ANDROID, new StringBody("")); } String url = getSetViUrl(group); postMultipartEntity(entity,url); }
/** * 设置用户所在组织所用的Windows客户端软件的Logo * * @param windowsLogoFile * 为null时代表清除Logo。 * @throws Exception */ public void setViWindowsLogo(File windowsLogoFile,String group) throws Exception { MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8")); if (windowsLogoFile != null) { entity.addPart(LOGO_FOR_WINDOWS, new FileBody(windowsLogoFile)); } else { entity.addPart(LOGO_FOR_WINDOWS, new StringBody("")); } String url = getSetViUrl(group); postMultipartEntity(entity,url); }