@Test public void testFormParamWithFile() throws IOException, URISyntaxException { HttpURLConnection connection = request("/test/v1/testFormParamWithFile", HttpMethod.POST); File file = new File(Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").toURI()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); builder.addPart("form", fileBody); HttpEntity build = builder.build(); connection.setRequestProperty("Content-Type", build.getContentType().getValue()); try (OutputStream out = connection.getOutputStream()) { build.writeTo(out); } InputStream inputStream = connection.getInputStream(); String response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); assertEquals(response, file.getName()); }
@Test public void testSingleFileUpload() throws IOException { // given File file = new File(UUID.randomUUID().toString()); InputStream attachment = Resources.getResource("attachment.txt").openStream(); FileUtils.copyInputStreamToFile(attachment, file); // when WebResponse response = WebRequest.post("/singlefile") .withFileBody("file", new FileBody(file)) .execute(); // then assertThat(response, not(nullValue())); assertThat(response.getStatusCode(), equalTo(StatusCodes.OK)); assertThat(response.getContent(), equalTo("This is an attachment")); file.delete(); }
@Test public void testMultiFileUpload() throws IOException { // given File file1 = new File(UUID.randomUUID().toString()); File file2 = new File(UUID.randomUUID().toString()); InputStream attachment1 = Resources.getResource("attachment.txt").openStream(); InputStream attachment2 = Resources.getResource("attachment.txt").openStream(); FileUtils.copyInputStreamToFile(attachment1, file1); FileUtils.copyInputStreamToFile(attachment2, file2); // when WebResponse response = WebRequest.post("/multifile") .withFileBody("file1", new FileBody(file1)) .withFileBody("file2", new FileBody(file2)) .execute(); // then assertThat(response, not(nullValue())); assertThat(response.getStatusCode(), equalTo(StatusCodes.OK)); assertThat(response.getContent(), equalTo("This is an attachmentThis is an attachment2")); file1.delete(); file2.delete(); }
private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); //httppost.setHeader("Cookie", sidcookie+";"+mysessioncookie); file = new File("h:/UploadingdotcomUploaderPlugin.java"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("notprivate", new StringBody("false")); mpEntity.addPart("folder", new StringBody("/")); mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into zippyshare.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } downloadlink=parseResponse(uploadresponse, "value=\"http://", "\""); downloadlink="http://"+downloadlink; System.out.println("Download Link : "+downloadlink); httpclient.getConnectionManager().shutdown(); }
private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); file = new File("h:/UploadingdotcomUploaderPlugin.java"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("emai", new StringBody("Free")); mpEntity.addPart("upload_range", new StringBody("1")); mpEntity.addPart("upfile_0", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into MegaShare.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); uploadresponse = response.getLastHeader("Location").getValue(); System.out.println("Upload response : "+uploadresponse); System.out.println(response.getStatusLine()); httpclient.getConnectionManager().shutdown(); }
public static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(postURL); File file = new File("d:/hai.html"); System.out.println(ukeycookie); httppost.setHeader("Cookie", ukeycookie + ";" + skeycookie + ";" + usercookie); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into mediafire..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Getting upload response key value.........."); uploadresponsekey = EntityUtils.toString(resEntity); getUploadResponseKey(); System.out.println("upload resoponse key " + uploadresponsekey); } }
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(); }
public static void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); //reqEntity.addPart("string_field",new StringBody("field value")); FileBody bin = new FileBody(new File("/home/vigneshwaran/VIGNESH/naruto.txt")); reqEntity.addPart("fff", bin); httppost.setEntity(reqEntity); System.out.println("Now uploading your file into 2shared.com. Please wait......................"); HttpResponse response = httpclient.execute(httppost); // HttpEntity resEntity = response.getEntity(); // // if (resEntity != null) { // String page = EntityUtils.toString(resEntity); // System.out.println("PAGE :" + page); // } }
private static void fileUpload() throws Exception { file = new File("/home/vigneshwaran/VIGNESH/dinesh.txt"); httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("ssd", new StringBody(ssd)); mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into slingfile.com"); HttpResponse response = httpclient.execute(httppost); // HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); }
private static void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", sidcookie); file = new File("h:/install.txt"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("filepc", cbFile); mpEntity.addPart("server", new StringBody(server)); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into uploadbox.com"); HttpResponse response = httpclient.execute(httppost); System.out.println(response.getStatusLine()); uploadresponse = response.getLastHeader("Location").getValue(); uploadresponse = getData(uploadresponse); downloadlink = parseResponse(uploadresponse, "name=\"loadlink\" id=\"loadlink\" class=\"text\" onclick=\"this.select();\" value=\"", "\""); deletelink = parseResponse(uploadresponse, "name=\"deletelink\" id=\"deletelink\" class=\"text\" onclick=\"this.select();\" value=\"", "\""); System.out.println("Download link " + downloadlink); System.out.println("deletelink : " + deletelink); }
public static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); file = new File("/home/vigneshwaran/dinesh.txt"); HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", langcookie + ";" + sessioncookie + ";" + mailcookie + ";" + namecookie + ";" + rolecookie + ";" + orderbycookie + ";" + directioncookie + ";"); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("files[]", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into wupload..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 302 && response.getFirstHeader("Location").getValue().contains("upload/done/")) { System.out.println("Upload successful :)"); } else { System.out.println("Upload failed :("); } }
private static void fileUpload() throws Exception { file = new File("C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\Sample Pictures\\Sunset.jpg"); httpclient = new DefaultHttpClient(); //http://upload3.divshare.com/cgi-bin/upload.cgi?sid=8ef15852c69579ebb2db1175ce065ba6 HttpPost httppost = new HttpPost(downURL + "cgi-bin/upload.cgi?sid=" + sid); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("file[0]", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into divshare.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(resEntity)); }
private static void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); file = new File("h:/Sakura haruno.jpg"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("Filedata", cbFile); // mpEntity.addPart("server", new StringBody(server)); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into ugotfile.com"); HttpResponse response = httpclient.execute(httppost); System.out.println(response.getStatusLine()); if (response != null) { uploadresponse = EntityUtils.toString(response.getEntity()); } System.out.println("Upload Response : " + uploadresponse); downloadlink = parseResponse(uploadresponse, "[\"", "\""); downloadlink = downloadlink.replaceAll("\\\\/", "/"); deletelink = parseResponse(uploadresponse, "\",\"", "\""); deletelink = deletelink.replaceAll("\\\\/", "/"); System.out.println("Download Link : " + downloadlink); System.out.println("Delete Link : " + deletelink); }
public static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); file = new File("C:\\Documents and Settings\\dinesh\\Desktop\\GeDotttUploaderPlugin.java"); HttpPost httppost = new HttpPost("https://docs.zoho.com/uploadsingle.do?isUploadStatus=false&folderId=0&refFileElementId=refFileElement0"); httppost.setHeader("Cookie", cookies.toString()); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("multiupload_file", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into zoho docs..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { String tmp = EntityUtils.toString(resEntity); // System.out.println(tmp); if(tmp.contains("File Uploaded Successfully")) System.out.println("File Uploaded Successfully"); } // uploadresponse = response.getLastHeader("Location").getValue(); // System.out.println("Upload response : " + uploadresponse); }
/** * Handles conversion from file to file with given File object * @param dest The output file object * @return True on success, false on error * @throws IOException */ private boolean convertFromFileToFile(File dest) throws IOException { if (!this.getInputFile().exists()) { throw new IllegalArgumentException("MsWordToImageConvert: Input file was not found at '" + this.input.getValue() + "'"); } HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(this.constructMsWordToImageAddress(new HashMap<>())); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("file_contents", new FileBody(this.getInputFile())); post.setEntity(builder.build()); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); try (FileOutputStream fileOS = new FileOutputStream(dest)) { entity.writeTo(fileOS); fileOS.flush(); } return true; }
private void performUpload() { Path gzLog = compressLog(); try (CloseableHttpClient client = buildHttpClient()) { HttpPost post = new HttpPost(CRASH_REPORT_URL); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody logFile = new FileBody(gzLog.toFile(), ContentType.DEFAULT_BINARY); builder.addPart("log", logFile); StringBody uid = new StringBody(userId, ContentType.TEXT_PLAIN); builder.addPart("uid", uid); HttpEntity postEntity = builder.build(); post.setEntity(postEntity); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { logger.debug("Error uploading crash report: {}", response.getStatusLine()); } } catch (IOException e) { logger.error("Error uploading crash report: {}", e.getLocalizedMessage()); } }
/** * 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("bundle_file", bundleBody) .addPart("job_options", 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; }
/** * 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 String httpsPost(String url, final File file) throws ParseException, IOException, JSONException { HttpPost hp = new HttpPost(UPDATE_URL); MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create(); // 可以直接addBinary multiPartEntityBuilder.addPart("pic", new FileBody(file, ContentType.create("application/octet-stream", Consts.UTF_8), "pic")); multiPartEntityBuilder.setCharset(Consts.UTF_8); // 可以直接addText multiPartEntityBuilder.addPart("access_token", new StringBody(ACCESSION_TOKEN, ContentType.create("text/plain", Consts.UTF_8))); multiPartEntityBuilder.addPart("status", new StringBody(String.valueOf(new Date().getTime()), ContentType.create("text/plain", Consts.UTF_8))); hp.setEntity(multiPartEntityBuilder.build()); HttpResponse response = client.execute(hp); String result = EntityUtils.toString(response.getEntity()); JSONObject json = new JSONObject(result); return (String) json.get("original_pic"); }
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; }
protected HttpPost setupPostWithFileName(HttpPost request, String fileName){ if (fileName == null || fileName.length() == 0) return request; ContentBody fileBody = new FileBody(new File(fileName), ContentType.DEFAULT_BINARY); MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setBoundary("boundaryABC--WebKitFormBoundaryGMApUciYGfDuPa49"); multipartEntity.addPart("file", fileBody); request.setEntity(multipartEntity.build()); // MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "boundaryABC--WebKitFormBoundaryGMApUciYGfDuPa49", Charset.forName("UTF-8")); // mpEntity.addPart("userfile", fileBody); // request.setEntity(mpEntity); // FileEntity entity = new FileEntity(new File(fileName), ContentType.APPLICATION_OCTET_STREAM); // BasicHeader basicHeader = new BasicHeader(HTTP.CONTENT_TYPE,"application/json"); //request.getParams().setBooleanParameter("http.protocol.expect-continue", false); // entity.setContentType(basicHeader); // request.setEntity(mpEntity); return request; }
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; }
public String postWithDigestAuth(final String url, final String file) { String responseBodyAsString = ""; try (CloseableHttpResponse response = httpClient.execute(targetHost, httpPost(url, MultipartEntityBuilder.create(). addPart("bin", new FileBody(new File(file))).build()), setAuth(targetHost, new DigestScheme()))) { responseBodyAsString = IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")); handler.logOutput("Http status: " + response.getStatusLine().getStatusCode(), true); InstallLog.getInstance().info("Http status: " + response.getStatusLine().getStatusCode()); } catch (IOException e) { final String messageError = "Error calling " + url + ": " + e.getMessage(); handler.emitError(messageError, messageError); InstallLog.getInstance().error(messageError); } return responseBodyAsString; }
public ContentBody toContentBody() { if (file != null) { return new FileBody(file) { @Override public String getFilename() { return fileName; } }; } else if (data != null) { return new ByteBufferBody(data) { @Override public String getFilename() { return fileName; } }; } else { // never happens throw new IllegalStateException("no upload data"); } }
/** * Upload file and set odo overrides and configuration of odo * * @param fileName File containing configuration * @param odoImport Import odo configuration in addition to overrides * @return If upload was successful */ public boolean uploadConfigurationAndProfile(String fileName, String odoImport) { File file = new File(fileName); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntityBuilder.addPart("fileData", fileBody); multipartEntityBuilder.addTextBody("odoImport", odoImport); try { JSONObject response = new JSONObject(doMultipartPost(BASE_BACKUP_PROFILE + "/" + uriEncode(this._profileName) + "/" + this._clientId, multipartEntityBuilder)); if (response.length() == 0) { return true; } else { return false; } } catch (Exception e) { return false; } }
@Override public void postFile(String url, Map<String, String> params, Callback callback, int timeout, File file) { try { HttpPost httpPost = new HttpPost(url); MultipartEntity multipartEntity = new MultipartEntity(); if (params!=null) for (Map.Entry<String, String> entry : params.entrySet()) multipartEntity.addPart(entry.getKey(), new StringBody(entry.getValue())); multipartEntity.addPart("file", new FileBody(file)); httpPost.setEntity(multipartEntity); sendRequest(getHttpClient(timeout), httpPost, callback); } catch (UnsupportedEncodingException e) { e.printStackTrace(); callback.error=e; callback.done(null); } }
private JSON request(HttpEntityEnclosingRequestBase req, Issue.NewAttachment... attachments) throws RestException, IOException { if (attachments != null) { req.setHeader("X-Atlassian-Token", "nocheck"); MultipartEntity ent = new MultipartEntity(); for(Issue.NewAttachment attachment : attachments) { String filename = attachment.getFilename(); Object content = attachment.getContent(); if (content instanceof byte[]) { ent.addPart("file", new ByteArrayBody((byte[]) content, filename)); } else if (content instanceof InputStream) { ent.addPart("file", new InputStreamBody((InputStream) content, filename)); } else if (content instanceof File) { ent.addPart("file", new FileBody((File) content, filename)); } else if (content == null) { throw new IllegalArgumentException("Missing content for the file " + filename); } else { throw new IllegalArgumentException( "Expected file type byte[], java.io.InputStream or java.io.File but provided " + content.getClass().getName() + " for the file " + filename); } } req.setEntity(ent); } return request(req); }
public static HttpResponseBean upload (String url, File file, Map<String, String> headers) throws IOException { @Cleanup final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost method = new HttpPost(url); final FileBody fileBody = new FileBody(file); MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", fileBody); method.setEntity(builder.build()); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { method.addHeader(new BasicHeader(header.getKey(), header.getValue())); } } @Cleanup final CloseableHttpResponse response = client.execute(method); final HttpResponseBean responseBean = new HttpResponseBean() .setEntityBytes(EntityUtils.toByteArray(response.getEntity())) .setHttpHeaders(response.getAllHeaders()) .setStatus(response.getStatusLine().getStatusCode()); return responseBean; }
/** * Computes the request payload. * * @return the payload containing the declared fields and files. */ public HttpEntity getEntity() { if (hasFile) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String, Object> part : parameters.entrySet()) { if (part.getValue() instanceof File) { hasFile = true; builder.addPart(part.getKey(), new FileBody((File) part.getValue())); } else { builder.addPart(part.getKey(), new StringBody(part.getValue().toString(), ContentType.APPLICATION_FORM_URLENCODED)); } } return builder.build(); } else { try { return new UrlEncodedFormEntity(getList(parameters), UTF_8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
public static MultipartEntity encodeMultipartParameters( final List<SimpleRequestParam> params) { if (CommonHelper.isEmpty(params)) { return null; } final MultipartEntity entity = new MultipartEntity(); try { for (final SimpleRequestParam param : params) { if (param.isFile()) { entity.addPart(param.getName(), new FileBody(param.getFile())); } else { entity.addPart( param.getName(), new StringBody(param.getValue(), Charset .forName(HTTP.UTF_8))); } } } catch (final UnsupportedEncodingException e) { e.printStackTrace(); } return entity; }
@Override protected HttpEntity buildEntity(ICommRestRequest restRequest) throws Exception{ ICommRestMultiPartRequest multiPartRequest = null; if( restRequest instanceof ICommRestMultiPartRequest){ multiPartRequest = (ICommRestMultiPartRequest) restRequest; } MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); if(multiPartRequest != null){ for(NameValuePair nvp:multiPartRequest.getNameValuePairs()) { if(nvp.getName().equalsIgnoreCase("File")) { File file = new File(nvp.getValue()); FileBody isb = new FileBody(file,"application/*"); entity.addPart(nvp.getName(), isb); } else { try{ LogHelper.w("RestRequest-Request",nvp.getName() + ": " + nvp.getValue()); ContentBody cb = new StringBody(nvp.getValue(),"", null); entity.addPart(nvp.getName(),cb); }catch(Exception ex){ LogHelper.e("MultiElementJsonRestHandler", "failed to add name value pair to HttpEntity with " + ex.getMessage()); } } } } return entity; }
public static HttpResponse doPost(String actionPath, Map<String, Object> params) throws ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(UrlConfig.BASE_URL + actionPath); MultipartEntity mulEntity = new MultipartEntity(); Set<String> keys = params.keySet(); for (String key : keys) { Object obj = params.get(key); if (obj instanceof File && obj != null) { mulEntity.addPart(key, new FileBody((File) obj)); } else { if(obj != null && !StringUtil.isEmpty(obj.toString())) { mulEntity.addPart(key, new StringBody(obj.toString(), Charset.forName(UrlConfig.CHART_SET))); } } } post.setEntity(mulEntity); return client.execute(post); }
private static MultipartEntityWithProgressListener getNewFileMultipartEntity(final String parentId, final String name, final File file) throws BoxRestException, UnsupportedEncodingException { MultipartEntityWithProgressListener me = new MultipartEntityWithProgressListener(HttpMultipartMode.BROWSER_COMPATIBLE); me.addPart(Constants.FOLDER_ID, new StringBody(parentId)); me.addPart(KEY_FILE_NAME, new FileBody(file, KEY_FILE_NAME, "", CharEncoding.UTF_8)); me.addPart(METADATA, getMetadataBody(parentId, name)); String date = ISO8601DateParser.toString(new Date(file.lastModified())); if (me.getPart(KEY_CONTENT_CREATED_AT) == null) { me.addPart(KEY_CONTENT_CREATED_AT, new StringBody(date)); } if (me.getPart(KEY_CONTENT_MODIFIED_AT) == null) { me.addPart(KEY_CONTENT_MODIFIED_AT, new StringBody(date)); } return me; }
public static HttpEntity makeMultipartEntity(List<NameValuePair> params, final Map<String, File> files) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //如果有SocketTimeoutException等情况,可修改这个枚举 //builder.setCharset(Charset.forName("UTF-8")); //不要用这个,会导致服务端接收不到参数 if (params != null && params.size() > 0) { for (NameValuePair p : params) { builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8")); } } if (files != null && files.size() > 0) { Set<Entry<String, File>> entries = files.entrySet(); for (Entry<String, File> entry : entries) { builder.addPart(entry.getKey(), new FileBody(entry.getValue())); } } return builder.build(); }
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; }