List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file)
From source file:com.liferay.ide.server.remote.ServerManagerConnection.java
public Object installApplication(String absolutePath, String appName, IProgressMonitor submon) throws APIException { try {/*from w w w.jav a 2s .c om*/ FileBody fileBody = new FileBody(new File(absolutePath)); MultipartEntity entity = new MultipartEntity(); entity.addPart("deployWar", fileBody); HttpPost httpPost = new HttpPost(); httpPost.setEntity(entity); Object response = httpJSONAPI(httpPost, _getDeployURI(appName)); if (response instanceof JSONObject) { JSONObject jsonObject = (JSONObject) response; if (_isSuccess(jsonObject)) { System.out.println("installApplication: Sucess.\n\n"); } else { if (_isError(jsonObject)) { return jsonObject.getString("error"); } else { return "installApplication error " + _getDeployURI(appName); } } } httpPost.releaseConnection(); } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } return null; }
From source file:org.n52.oss.ui.controllers.ScriptController.java
@RequestMapping(method = RequestMethod.POST, value = "/upload") public String processForm(@ModelAttribute(value = "uploadForm") uploadForm form, ModelMap map) { String s = form.getFile().getFileItem().getName(); MultipartEntity multipartEntity = new MultipartEntity(); UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();/*from ww w . j av a2 s . c o m*/ String token = userDetails.getPassword(); // upload the file File dest = new File(s); try { System.out.println("Chosen license:" + form.getLicense()); log.info("Chosen license:" + form.getLicense()); form.getFile().transferTo(dest); UserDetails details = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal(); multipartEntity.addPart("file", new FileBody(dest)); multipartEntity.addPart("user", new StringBody(details.getUsername())); multipartEntity.addPart("licenseCode", new StringBody(form.getLicense())); multipartEntity.addPart("auth_token", new StringBody(token)); HttpPost post = new HttpPost(OSSConstants.BASE_URL + "/OpenSensorSearch/script/submit"); post.setEntity(multipartEntity); org.apache.http.client.HttpClient client = new DefaultHttpClient(); HttpResponse resp; resp = client.execute(post); int responseCode = resp.getStatusLine().getStatusCode(); StringBuilder builder = new StringBuilder(); String str = null; BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); while ((str = reader.readLine()) != null) builder.append(str); System.out.println("return id:" + builder.toString()); log.info("return id:" + builder.toString()); if (responseCode == 200) { map.addAttribute("harvestSuccess", true); map.addAttribute("resultScript", builder.toString()); map.addAttribute("license", form.getLicense()); return "script/status"; } else { map.addAttribute("harvestError", true); return "script/status"; } } catch (Exception e) { map.addAttribute("errorMSG", e); return "script/status?fail"; } }
From source file:com.questdb.test.tools.HttpTestUtils.java
private static int upload(File file, String url, String schema, StringBuilder response) throws IOException { HttpPost post = new HttpPost(url); try (CloseableHttpClient client = HttpClients.createDefault()) { MultipartEntityBuilder b = MultipartEntityBuilder.create(); if (schema != null) { b.addPart("schema", new StringBody(schema, ContentType.TEXT_PLAIN)); }//from w w w. ja va 2 s . c om b.addPart("data", new FileBody(file)); post.setEntity(b.build()); HttpResponse r = client.execute(post); if (response != null) { InputStream is = r.getEntity().getContent(); int n; while ((n = is.read()) > 0) { response.append((char) n); } is.close(); } return r.getStatusLine().getStatusCode(); } }
From source file:com.cloudera.livy.client.http.LivyConnection.java
synchronized <V> V post(File f, Class<V> retType, String paramName, String uri, Object... uriParams) throws Exception { HttpPost post = new HttpPost(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart(paramName, new FileBody(f)); post.setEntity(builder.build());// ww w . j a v a 2 s .c o m return sendRequest(post, retType, uri, uriParams); }
From source file:com.phodev.http.tools.RequestEntity.java
/** * POST//w ww . j a va 2 s. c o m * * <pre> * RequestMethod{@link ConnectionHelper.RequestMethod#POST_WITH_FILE}}? * </pre> * * @param postValues * @param files * @param charset */ public RequestEntity setPostEntitiy(List<NameValuePair> postValues, String charset, Map<String, File> files) { Charset c = null; try { c = Charset.forName(charset); Charset.defaultCharset(); } catch (Exception e) { c = null; } MultipartEntity entity; HttpMultipartMode mode = HttpMultipartMode.BROWSER_COMPATIBLE; if (c == null) { entity = new MultipartEntity(mode); } else { entity = new MultipartEntity(mode, null, c); } postEntity = entity; if (postValues != null) { for (NameValuePair v : postValues) { try { entity.addPart(v.getName(), new StringBody(v.getValue())); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } if (files != null) { Iterator<Entry<String, File>> iterator = files.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, File> entry = iterator.next(); entity.addPart(entry.getKey(), new FileBody(entry.getValue())); } } return this; }
From source file:org.jodconverter.task.OnlineConversionTask.java
@Override public void execute(final OfficeContext context) throws OfficeException { LOGGER.info("Executing online conversion task..."); final OnlineOfficeContext onlineContext = (OnlineOfficeContext) context; // Obtain a source file that can be loaded by office. If the source // is an input stream, then a temporary file will be created from the // stream. The temporary file will be deleted once the task is done. final File sourceFile = source.getFile(); try {/*from w w w . j a v a 2s. com*/ // Get the target file (which is a temporary file if the // output target is an output stream). final File targetFile = target.getFile(); try { // TODO: Add the ability to pass on a custom charset to FileBody // See https://github.com/LibreOffice/online/blob/master/wsd/reference.txt final HttpEntity entity = MultipartEntityBuilder.create().addPart("data", new FileBody(sourceFile)) .build(); // Use the fluent API to post the file and // save the response into the target file. final RequestConfig requestConfig = onlineContext.getRequestConfig(); final URIBuilder uriBuilder = new URIBuilder(buildUrl(requestConfig.getUrl())); // We suppose that the server supports custom load properties, // but LibreOffice does not support custom load properties, // only the sample web service do. addPropertiesToBuilder(uriBuilder, target.getFormat().getLoadProperties(), LOAD_PROPERTIES_PREFIX_PARAM); // We suppose that the server supports custom store properties, // but LibreOffice does not support custom store properties, // only the sample web service do. addPropertiesToBuilder(uriBuilder, target.getFormat().getStoreProperties(source.getFormat().getInputFamily()), STORE_PROPERTIES_PREFIX_PARAM); Executor.newInstance(onlineContext.getHttpClient()).execute( // Request.Post(buildUrl(requestConfig.getUrl())) Request.Post(uriBuilder.build()).connectTimeout(requestConfig.getConnectTimeout()) .socketTimeout(requestConfig.getSocketTimeout()).body(entity)) .saveContent(targetFile); // onComplete on target will copy the temp file to // the OutputStream and then delete the temp file // if the output is an OutputStream target.onComplete(targetFile); } catch (Exception ex) { LOGGER.error("Online conversion failed.", ex); final OfficeException officeEx = new OfficeException("Online conversion failed", ex); target.onFailure(targetFile, officeEx); throw officeEx; } } finally { // Here the source file is no longer required so we can delete // any temporary file that has been created if required. source.onConsumed(sourceFile); } }
From source file:interactivespaces.util.web.HttpClientHttpContentCopier.java
@Override public void copyTo(String destinationUri, File source, String sourceParameterName, Map<String, String> params) { FileBody contentBody = new FileBody(source); doCopyTo(destinationUri, sourceParameterName, params, contentBody); }
From source file:outfox.ynote.open.client.YNoteHttpUtils.java
/** * 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//from ww w .j a v a 2 s.co m * @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, null, Charset.forName("UTF-8")); 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; }
From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java
@Test public void testMultiPartRequest() throws IOException { TestHttpClient client = new TestHttpClient(); try {//w w w . ja v a 2s .c om String uri = DefaultServer.getDefaultServerURL() + "/servletContext/1"; HttpPost post = new HttpPost(uri); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, StandardCharsets.UTF_8); entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8)); entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile()))); post.setEntity(entity); HttpResponse result = client.execute(post); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); final String response = HttpClientUtils.readResponse(result); Assert.assertEquals("PARAMS:\n" + "name: formValue\n" + "filename: null\n" + "content-type: null\n" + "Content-Disposition: form-data; name=\"formValue\"\n" + "size: 7\n" + "content: myValue\n" + "name: file\n" + "filename: uploadfile.txt\n" + "content-type: application/octet-stream\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\n" + "Content-Type: application/octet-stream\n" + "size: 13\n" + "content: file contents\n", response); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.dmsl.anyplace.tasks.UploadRSSLogTask.java
@Override protected String doInBackground(Void... params) { try {/* w w w . j av a 2s.co 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!"; }