List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:com.woonoz.proxy.servlet.HttpEntityEnclosingRequestHandler.java
private HttpEntity createMultipartEntity(HttpServletRequest request) throws FileUploadException, IOException { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); MultipartEntity multipartEntity = new MultipartEntity(); FileItemIterator iterator = servletFileUpload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream fileItem = iterator.next(); final String partName = fileItem.getFieldName(); if (fileItem.isFormField()) { multipartEntity.addPart(partName, buildStringBody(fileItem)); } else {/* w w w .j av a 2 s. c o m*/ multipartEntity.addPart(partName, buildContentBodyFromFileItem(fileItem)); } } return multipartEntity; }
From source file:at.univie.sensorium.extinterfaces.HTTPSUploader.java
private String uploadFiles(List<File> files) { String result = ""; try {//w ww. j a v a 2s .co m if (URLUtil.isValidUrl(posturl)) { HttpClient httpclient = getNewHttpClient(); HttpPost httppost = new HttpPost(posturl); MultipartEntity mpEntity = new MultipartEntity(); // MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("username", new StringBody(username)); mpEntity.addPart("password", new StringBody(password)); for (File file : files) { Log.d(SensorRegistry.TAG, "preparing " + file.getName() + " for upload"); ContentBody cbFile = new FileBody(file, "application/json"); mpEntity.addPart(file.toString(), cbFile); } httppost.addHeader("username", username); httppost.addHeader("password", password); httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); String reply; InputStream in = response.getEntity().getContent(); StringBuilder sb = new StringBuilder(); try { int chr; while ((chr = in.read()) != -1) { sb.append((char) chr); } reply = sb.toString(); } finally { in.close(); } result = response.getStatusLine().toString(); Log.d(SensorRegistry.TAG, "Http upload completed with response: " + result + " " + reply); } else { result = "URL invalid"; Log.d(SensorRegistry.TAG, "Invalid http upload url, aborting."); } } catch (IllegalArgumentException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); } catch (FileNotFoundException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); } catch (ClientProtocolException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); } catch (IOException e) { result = "upload failed due to timeout"; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); } return result; }
From source file:org.marietjedroid.connect.MarietjeMessenger.java
/** * Sends a stream/*from w w w . j ava2s .com*/ * * FIXME probably massively broken * * @param token * @param stream * @param blocking */ public void sendStream(String token, ContentBody stream, boolean blocking) { if (!this.token.equals(token)) throw new IllegalArgumentException("Wrong token!"); MultipartEntity multipartStream = new MultipartEntity(); multipartStream.addPart("stream", stream); final HttpPost post = new HttpPost(String.format("http://%s:%s%s", host, port, path)); // FIXME sowieso stuk post.setEntity(multipartStream); Thread t = new Thread(new Runnable() { public void run() { try { httpClient.execute(post); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); t.start(); if (blocking) { try { t.join(); } catch (InterruptedException e) { } } }
From source file:com.glodon.paas.document.api.PerformanceRestAPITest.java
/** * multipart/* w w w . ja va 2 s. c o m*/ */ @Test public void testUploadFileForMultiPart() throws IOException { File parentFile = createFile("testUpload"); java.io.File file = new java.io.File("src/test/resources/file/testupload.file"); if (!file.exists()) { file = new java.io.File(tempUploadFile); } String uploadUrl = "/file/" + file.getName() + "?upload&position=0&type=path"; HttpPost post = createPost(uploadUrl); FileBody fileBody = new FileBody(file); StringBody sbId = new StringBody(parentFile.getId()); StringBody sbSize = new StringBody(String.valueOf(file.length())); StringBody sbName = new StringBody(file.getName()); StringBody sbPosition = new StringBody("0"); MultipartEntity entity = new MultipartEntity(); entity.addPart("fileId", sbId); entity.addPart("size", sbSize); entity.addPart("fileName", sbName); entity.addPart("position", sbPosition); entity.addPart("file", fileBody); post.setEntity(entity); String response = simpleCall(post); assertNotNull(response); File resultFile = convertString2Obj(response, new TypeReference<File>() { }); assertEquals(file.getName(), resultFile.getFullName()); assertTrue(file.length() == resultFile.getSize()); }
From source file:com.indigenedroid.app.volley.tools.MultiPartRequest.java
@Override public byte[] getBody() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); mEntity = new MultipartEntity(); FileInputStream fis;// w w w . j a v a 2s . c o m try { fis = new FileInputStream(fileUploads.get("portrait_file")); InputStreamBody body = new InputStreamBody(fis, getFileName(fileUploads.get("portrait_file").getAbsolutePath())); mEntity.addPart("portrait_file", body); try { mEntity.addPart("token", new StringBody(stringUploads.get("token"))); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //HttpEntity entity = new FileEntity(fileUploads.get("portrait_file"), "application/octet-stream"); try { mEntity.writeTo(bos); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bos.toByteArray(); //return super.getBody(); }
From source file:com.captchatrader.CaptchaTrader.java
/** * Submit a CAPTCHA already hosted on an existing website. * //from w w w . jav a 2s . c om * @param uri * The URI of the CAPTCHA image. * @return The decoded CAPTCHA. * @throws Any * exceptions sent by the server. */ public ResolvedCaptcha submit(URI uri) throws CaptchaTraderException, IOException { final URI requestUri = apiURI.resolve("submit"); final HttpPost request = new HttpPost(requestUri); final MultipartEntity entity = new MultipartEntity(); entity.addPart("api_key", new StringBody(applicationKey)); entity.addPart("username", new StringBody(username)); entity.addPart("password", new StringBody(password)); entity.addPart("value", new StringBody(uri.toString())); request.setEntity(entity); final List<Object> response = validate(execute(request)); return new ResolvedCaptcha(this, ((Long) response.get(0)).toString(), (String) response.get(1)); }
From source file:face4j.ResponderImpl.java
/** * @see {@link Responder#doPost(File, URI, List)} *///w w w . j a va2s. co m public String doPost(final File file, final URI uri, final List<NameValuePair> params) throws FaceClientException, FaceServerException { try { final MultipartEntity entity = new MultipartEntity(); if (logger.isInfoEnabled()) { logger.info("Adding image entity, size: [{}] bytes", file.length()); } entity.addPart("image", new FileBody(file)); try { for (NameValuePair nvp : params) { entity.addPart(nvp.getName(), new StringBody(nvp.getValue())); } } catch (UnsupportedEncodingException uee) { logger.error("Error adding entity", uee); throw new FaceClientException(uee); } postMethod.setURI(uri); postMethod.setEntity(entity); final long start = System.currentTimeMillis(); final HttpResponse response = httpClient.execute(postMethod); if (logger.isDebugEnabled()) { logger.debug("POST took {} (ms)", (System.currentTimeMillis() - start)); } return checkResponse(response); } catch (IOException ioe) { logger.error("Error while POSTing to {} ", uri, ioe); throw new FaceClientException(ioe); } }
From source file:name.richardson.james.maven.plugins.uploader.UploadMojo.java
public void execute() throws MojoExecutionException { this.getLog().info("Uploading project to BukkitDev"); final String gameVersion = this.getGameVersion(); final URIBuilder builder = new URIBuilder(); final MultipartEntity entity = new MultipartEntity(); HttpPost request;/*w w w . j av a 2 s .c om*/ // create the request builder.setScheme("http"); builder.setHost("dev.bukkit.org"); builder.setPath("/" + this.projectType + "/" + this.slug.toLowerCase() + "/upload-file.json"); try { entity.addPart("file_type", new StringBody(this.getFileType())); entity.addPart("name", new StringBody(this.project.getArtifact().getVersion())); entity.addPart("game_versions", new StringBody(gameVersion)); entity.addPart("change_log", new StringBody(this.changeLog)); entity.addPart("known_caveats", new StringBody(this.knownCaveats)); entity.addPart("change_markup_type", new StringBody(this.markupType)); entity.addPart("caveats_markup_type", new StringBody(this.markupType)); entity.addPart("file", new FileBody(this.getArtifactFile(this.project.getArtifact()))); } catch (final UnsupportedEncodingException e) { throw new MojoExecutionException(e.getMessage()); } // create the actual request try { request = new HttpPost(builder.build()); request.setHeader("User-Agent", "MavenCurseForgeUploader/1.0"); request.setHeader("X-API-Key", this.key); request.setEntity(entity); } catch (final URISyntaxException exception) { throw new MojoExecutionException(exception.getMessage()); } this.getLog().debug(request.toString()); // send the request and handle any replies try { final HttpClient client = new DefaultHttpClient(); final HttpResponse response = client.execute(request); switch (response.getStatusLine().getStatusCode()) { case 201: this.getLog().info("File uploaded successfully."); break; case 403: this.getLog().error( "You have not specifed your API key correctly or do not have permission to upload to that project."); break; case 404: this.getLog().error("Project was not found. Either it is specified wrong or been renamed."); break; case 422: this.getLog().error("There was an error in uploading the plugin"); this.getLog().debug(request.toString()); this.getLog().debug(EntityUtils.toString(response.getEntity())); break; default: this.getLog().warn("Unexpected response code: " + response.getStatusLine().getStatusCode()); break; } } catch (final ClientProtocolException exception) { throw new MojoExecutionException(exception.getMessage()); } catch (final IOException exception) { throw new MojoExecutionException(exception.getMessage()); } }
From source file:org.dataconservancy.ui.it.support.MetadataFileRequest.java
public HttpPost asHttpPost() { String depositUrl = urlConfig.getMetadataFileUrl().toString(); HttpPost post = new HttpPost(depositUrl); MultipartEntity entity = new MultipartEntity(); try {/*from www. j av a 2 s. c om*/ entity.addPart("parentID", new StringBody(parentId, Charset.forName("UTF-8"))); if (name != null && !name.isEmpty()) { entity.addPart("metadataFile.name", new StringBody(name, Charset.forName("UTF-8"))); } if (metadataFormat != null && !metadataFormat.isEmpty()) { entity.addPart("metadataFile.metadataFormatId", new StringBody(metadataFormat, Charset.forName("UTF-8"))); } if (id != null && !id.isEmpty()) { entity.addPart("metadataFileID", new StringBody(id, Charset.forName("UTF-8"))); } if (isCollection) { entity.addPart("redirectUrl", new StringBody("viewCollectionDetails", Charset.forName("UTF-8"))); } entity.addPart(event, new StringBody(event, Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } if (fileToDeposit != null) { FileBody fileBody = new FileBody(fileToDeposit); entity.addPart("uploadedFile", fileBody); post.setEntity(entity); } return post; }
From source file:com.parworks.androidlibrary.ar.ARSites.java
/** * Synchronously augment an image towards a list of sites * /*from w ww .j a v a 2s. com*/ * @param image * an inputstream containing the image * @return the augmented data */ public AugmentedData augmentImageGroup(List<String> sites, InputStream image) { Map<String, String> params = new HashMap<String, String>(); MultipartEntity imageEntity = new MultipartEntity(); InputStreamBody imageInputStreamBody = new InputStreamBody(image, "image"); imageEntity.addPart("image", imageInputStreamBody); for (String siteId : sites) { try { imageEntity.addPart("site", new StringBody(siteId)); } catch (UnsupportedEncodingException e) { throw new ARException(e); } } HttpUtils httpUtils = new HttpUtils(mApiKey, mTime, mSignature); HttpResponse serverResponse = httpUtils .doPost(HttpUtils.PARWORKS_API_BASE_URL + HttpUtils.AUGMENT_IMAGE_GROUP_PATH, imageEntity, params); HttpUtils.handleStatusCode(serverResponse.getStatusLine().getStatusCode()); ARResponseHandler responseHandler = new ARResponseHandlerImpl(); AugmentImageGroupResponse augmentImageGroupResponse = responseHandler.handleResponse(serverResponse, AugmentImageGroupResponse.class); if (augmentImageGroupResponse.getSuccess() == false) { throw new ARException( "Successfully communicated with the server, failed to augment the image. Perhaps the site does not exist or has no overlays."); } // List<AugmentedData> result = new ArrayList<AugmentedData>(); // for(SiteImageBundle bundle : augmentImageGroupResponse.getCandidates()) { // AugmentedData augmentedImage = null; // while (augmentedImage == null) { // augmentedImage = getAugmentResult(bundle.getSite(), bundle.getImgId()); // } // result.add(augmentedImage); // } List<AugmentedData> result = getAugmentedImageGroupResult(augmentImageGroupResponse.getSitesToCheck(), augmentImageGroupResponse.getImgId()); // combine different results AugmentedData finalData = null; for (AugmentedData data : result) { if (data.isLocalization()) { if (finalData == null) { finalData = data; } else { finalData.getOverlays().addAll(data.getOverlays()); } } } return finalData; }