List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:at.ac.tuwien.big.testsuite.impl.validator.WaiValidator.java
@Override public ValidationResult validate(File fileToValidate, String exerciseId) throws Exception { CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpPost request = new HttpPost("http://localhost:8080/" + contextPath + "/checker/index.php"); List<ValidationResultEntry> validationResultEntries = new ArrayList<>(); try {/*ww w . j av a 2 s. com*/ MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("uri", new StringBody("")); multipartEntity.addPart("MAX_FILE_SIZE", new StringBody("52428800")); multipartEntity.addPart("uploadfile", new FileBody(fileToValidate, "text/html")); multipartEntity.addPart("validate_file", new StringBody("Check It")); multipartEntity.addPart("pastehtml", new StringBody("")); multipartEntity.addPart("radio_gid[]", new StringBody("8")); multipartEntity.addPart("checkbox_gid[]", new StringBody("8")); multipartEntity.addPart("rpt_format", new StringBody("1")); request.setEntity(multipartEntity); Document doc = httpClient.execute(request, new DomResponseHandler(httpClient, request), httpContext); Element errorsContainer = DomUtils.byId(doc.getDocumentElement(), "AC_errors"); String title = ""; StringBuilder descriptionSb = new StringBuilder(); boolean descriptionStarted = false; for (Element e : DomUtils.asList(errorsContainer.getChildNodes())) { if ("h3".equals(e.getTagName())) { if (descriptionStarted) { validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(), ValidationResultEntryType.ERROR)); } title = e.getTextContent(); descriptionSb.setLength(0); descriptionStarted = false; } else if ("div".equals(e.getTagName()) && e.getAttribute("class").contains("gd_one_check")) { if (descriptionStarted) { descriptionSb.append('\n'); } if (extractDescription(e, descriptionSb)) { descriptionStarted = true; } } } if (descriptionStarted) { validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(), ValidationResultEntryType.ERROR)); } } finally { request.releaseConnection(); } return new DefaultValidationResult("WAI Validation", fileToValidate.getName(), new DefaultValidationResultType("WAI"), validationResultEntries); }
From source file:org.andrico.andjax.http.HttpMessageFactory.java
/** * Create a new http uri request with more standard datatypes. * /* w w w.j av a 2 s. c om*/ * @param url The url to push the request to. * @param params String parameters to pass in the post. * @throws URISyntaxException */ public HttpMessage create(String url, Map<String, String> params) throws URISyntaxException { MultipartEntity multipartEntity = null; if (params != null) { multipartEntity = new MultipartEntity(); for (final String key : params.keySet()) { try { multipartEntity.addPart(key, new StringBody(params.get(key))); } catch (final UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return this.createFromParts(url, multipartEntity); }
From source file:com.dmsl.anyplace.tasks.UploadRSSLogTask.java
@Override protected String doInBackground(Void... params) { try {//from w ww . java 2s.c o m JSONObject j; j = new JSONObject(); j.put("username", username); j.put("password", password); String json = j.toString(); File rsslog = new File(this.file); if (rsslog.exists() == false) { exceptionOccured = true; return "File not found"; } Log.d("radio upload", rsslog.toString()); String response; HttpClient httpclient = new DefaultHttpClient(); httppost = new HttpPost(AnyplaceAPI.getRadioUploadUrl()); MultipartEntity entity = new MultipartEntity(); entity.addPart("radiomap", new FileBody(rsslog)); entity.addPart("json", new StringBody(json)); ProgressCallback progressCallback = new ProgressCallback() { @Override public void progress(float progress) { if (currentProgress != (int) (progress)) { currentProgress = (int) progress; publishProgress(currentProgress); } } }; httppost.setEntity(new ProgressHttpEntityWrapper(entity, progressCallback)); HttpResponse httpresponse = httpclient.execute(httppost); HttpEntity resEntity = httpresponse.getEntity(); response = EntityUtils.toString(resEntity); Log.d("radio upload", "response: " + response); j = new JSONObject(response); if (j.getString("status").equalsIgnoreCase("error")) { exceptionOccured = true; return "Error: " + j.getString("message"); } } catch (JSONException e) { exceptionOccured = true; Log.d("upload rss log", e.getMessage()); return "Cannot upload RSS log. JSONException occurred[ " + e.getMessage() + " ]"; } catch (ParseException e) { exceptionOccured = true; Log.d("upload rss log", e.getMessage()); return "Cannot upload RSS log. ParseException occurred[ " + e.getMessage() + " ]"; } catch (IOException e) { exceptionOccured = true; Log.d("upload rss log", e.getMessage()); if (httppost != null && httppost.isAborted()) { return "Uploading cancelled!"; } else { return "Cannot upload RSS log. IOException occurred[ " + e.getMessage() + " ]"; } } return "Successfully uploaded RSS log!"; }
From source file:org.trpr.platform.batch.impl.job.ha.service.SyncServiceImpl.java
/** * Interface Method Implementation/*from www. j ava 2 s .c o m*/ * @see SyncService#pushJobToHost(String, String) */ public boolean pushJobToHost(String jobName, String serverName) { serverName = SyncServiceImpl.PROTOCOL + serverName + SynchronizationController.PUSH_URL; HttpPost postRequest = new HttpPost(serverName); try { MultipartEntity multiPartEntity = new MultipartEntity(); multiPartEntity.addPart("jobName", new StringBody(jobName)); FileBody fileBody = new FileBody(this.jobConfigService.getJobConfig(jobName).getFile(), "application/octect-stream"); multiPartEntity.addPart("jobConfig", fileBody); if (this.jobConfigService.getJobDependencyList(jobName) != null) { for (String dependency : this.jobConfigService.getJobDependencyList(jobName)) { File depFile = new File( this.jobConfigService.getJobStoreURI(jobName).getPath() + "/lib/" + dependency); FileBody depFileBody = new FileBody(depFile); multiPartEntity.addPart("depFiles[]", depFileBody); } } postRequest.setEntity(multiPartEntity); } catch (UnsupportedEncodingException ex) { LOGGER.error("Error while forming multiPart request", ex); } catch (IOException e) { LOGGER.error("Error while forming multiPart request", e); } String retValue = org.trpr.platform.batch.impl.job.ha.service.FileUpload.executeRequest(postRequest); LOGGER.info("Server returns: " + retValue.trim()); if (retValue.trim().equalsIgnoreCase(SyncServiceImpl.SUCCESS_STRING)) { return true; } return false; }
From source file:com.qcloud.CloudClient.java
public String post(String url, Map<String, String> header, Map<String, Object> body, byte[] data) throws UnsupportedEncodingException, IOException { HttpPost httpPost = new HttpPost(url); httpPost.setHeader("accept", "*/*"); httpPost.setHeader("connection", "Keep-Alive"); httpPost.setHeader("user-agent", "qcloud-java-sdk"); if (header != null) { for (String key : header.keySet()) { httpPost.setHeader(key, header.get(key)); }//w w w. ja va 2s . c o m } if (false == header.containsKey("Content-Type") || header.get("Content-Type").equals("multipart/form-data")) { MultipartEntity multipartEntity = new MultipartEntity(); if (body != null) { for (String key : body.keySet()) { multipartEntity.addPart(key, new StringBody(body.get(key).toString())); } } if (data != null) { ContentBody contentBody = new ByteArrayBody(data, "qcloud"); multipartEntity.addPart("fileContent", contentBody); } httpPost.setEntity(multipartEntity); } else { if (data != null) { String strBody = new String(data); StringEntity stringEntity = new StringEntity(strBody); httpPost.setEntity(stringEntity); } } // HttpHost proxy = new HttpHost("127.0.0.1",8888); // mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy); HttpResponse httpResponse = mClient.execute(httpPost); int code = httpResponse.getStatusLine().getStatusCode(); return EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); }
From source file:com.mashape.unirest.request.body.MultipartBody.java
public HttpEntity getEntity() { if (hasFile) { MultipartEntity entity = new MultipartEntity(); for (Entry<String, Object> part : parameters.entrySet()) { if (part.getValue() instanceof File) { hasFile = true;/*from ww w .ja v a2 s. c o m*/ entity.addPart(part.getKey(), new FileBody((File) part.getValue())); } else { try { entity.addPart(part.getKey(), new StringBody(part.getValue().toString(), Charset.forName(UTF_8))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } return entity; } else { try { return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
From source file:com.fly1tkg.streamfileupload.FileUploadFacade.java
public void post(final String url, final String fileKey, final File file, final String contentType, final Map<String, String> params, final FileUploadCallback callback) { if (null == callback) { throw new RuntimeException("FileUploadCallback should not be null."); }/*from ww w .j a va 2 s .c o m*/ ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(new Runnable() { public void run() { try { HttpPost httpPost = new HttpPost(url); FileBody fileBody; if (null == contentType) { fileBody = new FileBody(file); } else { fileBody = new FileBody(file, contentType); } MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); if (null == fileKey) { entity.addPart(DEFAULT_FILE_KEY, fileBody); } else { entity.addPart(fileKey, fileBody); } if (null != params) { for (Map.Entry<String, String> e : params.entrySet()) { entity.addPart(e.getKey(), new StringBody(e.getValue())); } } httpPost.setEntity(entity); upload(httpPost, callback); } catch (UnsupportedEncodingException e) { callback.onFailure(-1, null, e); } } }); }
From source file:net.idea.opentox.cli.dataset.DatasetClient.java
@Override protected HttpEntity createPOSTEntity(Dataset dataset, List<POLICY_RULE> accessRights) throws InvalidInputException, Exception { if (dataset.getInputData() == null || dataset.getInputData().getInputFile() == null) throw new InvalidInputException("File to import not defined!"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8); entity.addPart(_WEBFORM.title.name(), new StringBody(dataset.getMetadata().getTitle(), utf8)); entity.addPart(_WEBFORM.seeAlso.name(), new StringBody(dataset.getMetadata().getSeeAlso(), utf8)); entity.addPart(_WEBFORM.license.name(), new StringBody(dataset.getMetadata().getRights() == null ? "" : (dataset.getMetadata().getRights().getURI() == null ? "" : dataset.getMetadata().getRights().getURI()), utf8));//ww w. j av a 2s. co m entity.addPart(_WEBFORM.match.name(), new StringBody(dataset.getInputData().getImportMatchMode().name(), utf8)); entity.addPart(_WEBFORM.file.name(), new FileBody(dataset.getInputData().getInputFile())); return entity; }
From source file:eu.prestoprime.plugin.mserve.client.MServeClient.java
/** * Uploads a file on MServe and returns its fileID * /*from w ww .j av a 2s . co m*/ * @param file * @return * @throws MServeException */ public String uploadFile(File file) throws MServeException { try { URL url = new URL(host + "/auths/" + serviceID + "/mfiles/"); logger.debug("MServe URL: " + url.toString()); HttpClient client = new DefaultHttpClient(); HttpUriRequest request = new HttpPost(url.toString()); request.setHeader("Accept", "application/json"); MultipartEntity part = new MultipartEntity(); part.addPart("file", new FileBody(file)); ((HttpPost) request).setEntity(part); HttpEntity stream = client.execute(request).getEntity(); InputStream istream = stream.getContent(); BufferedReader buf = new BufferedReader(new InputStreamReader(istream)); String line; StringBuffer sb = new StringBuffer(); while (null != ((line = buf.readLine()))) { sb.append(line.trim()); } buf.close(); istream.close(); logger.debug(sb.toString()); JSONObject response = new JSONObject(sb.toString()); return response.getString("id"); } catch (MalformedURLException e) { throw new MServeException("Bad REST interface..."); } catch (IOException e) { throw new MServeException("Unable to make IO..."); } catch (JSONException e) { throw new MServeException("Bad JSON response..."); } }
From source file:com.shmsoft.dmass.lotus.NSFParser.java
private boolean submitProcessing(String url, String taskId, String nsfFile) { File file = new File(nsfFile); HttpClient httpClient = new DefaultHttpClient(); try {//from w w w . ja va 2s.c om HttpPost post = new HttpPost(url + "/submit-processing.html"); MultipartEntity entity = new MultipartEntity(); entity.addPart("file", new FileBody(file)); entity.addPart("taskId", new StringBody(taskId)); post.setEntity(entity); HttpResponse response = httpClient.execute(post); getResponseMessage(response); } catch (Exception e) { System.out.println("NSFParser -- Problem sending data: " + e.getMessage()); return false; } return true; }