List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity
public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams)
From source file:com.linkedin.pinot.common.utils.FileUploadUtils.java
public static int sendFile(final String host, final String port, final String path, final String fileName, final InputStream inputStream, final long lengthInBytes, SendFileMethod httpMethod) { EntityEnclosingMethod method = null; try {/*ww w. j a va2 s .c o m*/ method = httpMethod.forUri("http://" + host + ":" + port + "/" + path); Part[] parts = { new FilePart(fileName, new PartSource() { @Override public long getLength() { return lengthInBytes; } @Override public String getFileName() { return "fileName"; } @Override public InputStream createInputStream() throws IOException { return new BufferedInputStream(inputStream); } }) }; method.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams())); FILE_UPLOAD_HTTP_CLIENT.executeMethod(method); if (method.getStatusCode() >= 400) { String errorString = "POST Status Code: " + method.getStatusCode() + "\n"; if (method.getResponseHeader("Error") != null) { errorString += "ServletException: " + method.getResponseHeader("Error").getValue(); } throw new HttpException(errorString); } return method.getStatusCode(); } catch (Exception e) { LOGGER.error("Caught exception while sending file: {}", fileName, e); Utils.rethrowException(e); throw new AssertionError("Should not reach this"); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:com.mercatis.lighthouse3.commons.commons.HttpRequest.java
/** * This method performs a file upload via multipart POST request. * * @param url the URL against which the file upload is performed * @param file the file to upload * @param postParameters any additional parameters to add to the POST request * @return the data returned by the web server * @throws HttpException in case a communication error occurred. *//*from w w w . ja va 2 s . co m*/ public String postFileUpload(String url, File file, Map<String, String> postParameters) { PostMethod filePost = null; try { filePost = new PostMethod(url); Part[] mimeParts = new Part[postParameters.size() + 1]; mimeParts[0] = new FilePart(file.getName(), file); int p = 1; for (String parameterName : postParameters.keySet()) { mimeParts[p] = new StringPart(parameterName, postParameters.get(parameterName)); p++; } filePost.setRequestEntity(new MultipartRequestEntity(mimeParts, filePost.getParams())); } catch (Exception anyProblem) { throw new HttpException("A problem occurred while constructing file upload request", anyProblem); } int resultCode = 0; String resultBody = null; try { resultCode = this.httpClient.executeMethod(filePost); resultBody = filePost.getResponseBodyAsString(); if (resultCode != 200) { throw new HttpException(resultBody, null); } } catch (HttpException httpException) { throw new HttpException("HTTP file upload failed", httpException); } catch (IOException ioException) { throw new HttpException("HTTP file upload failed", ioException); } finally { filePost.releaseConnection(); } return resultBody; }
From source file:com.owncloud.android.CrashlogSendActivity.java
@Override public void onClick(DialogInterface dialog, final int which) { new Thread(new Runnable() { @Override//from w ww .ja va 2s .com public void run() { // TODO Auto-generated method stub File file = new File(mLogFilename); if (which == Dialog.BUTTON_POSITIVE) { try { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(CRASHLOG_SUBMIT_URL); Part[] parts = { new FilePart("crashfile", file) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); client.executeMethod(post); post.releaseConnection(); } catch (Exception e) { e.printStackTrace(); } } file.delete(); finish(); } }).start(); }
From source file:com.apatar.core.ApatarHttpClient.java
public String sendPostHttpQuery(String url, HashMap<String, String> params) throws IOException { int size = params.size(); Part[] parts = new Part[size]; int i = 0;//from w w w . j a v a 2 s. co m for (String param : params.keySet()) { parts[i++] = new StringPart(param, params.get(param)); } PostMethod method = new PostMethod(url); method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); return sendHttpQuery(method); }
From source file:edu.caltech.ipac.firefly.server.util.multipart.MultiPartPostBuilder.java
/** * Post this multipart request.//from w ww . j a v a2 s . co m * @param responseBody the response is written into this OutputStream. * @return a MultiPartRespnse which contains headers, status, and status code. */ public MultiPartRespnse post(OutputStream responseBody) { if (targetURL == null || parts.size() == 0) { return null; } logStart(); PostMethod filePost = new PostMethod(targetURL); for (Param p : headers) { filePost.addRequestHeader(p.getName(), p.getValue()); } try { filePost.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), filePost.getParams())); HttpServices.executeMethod(filePost, userId, passwd); MultiPartRespnse resp = new MultiPartRespnse(filePost.getResponseHeaders(), filePost.getStatusCode(), filePost.getStatusText()); if (responseBody != null) { readBody(responseBody, filePost.getResponseBodyAsStream()); } return resp; } catch (Exception ex) { LOG.error(ex, "Error while posting multipart request to" + targetURL); return null; } finally { filePost.releaseConnection(); } }
From source file:eu.impact_project.iif.t2.client.HelperTest.java
/** * Test of parseRequest method, of class Helper. *///from ww w .j a v a 2 s. c om @Test public void testParseRequest() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); URL url = this.getClass().getResource("/prueba.txt"); File testFile = new File(url.getFile()); Part[] parts = new Part[] { new StringPart("user", "user"), new FilePart("file_workflow", testFile), new FilePart("comon_file", testFile) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray()); when(request.getInputStream()).thenReturn(new ServletInputStream() { @Override public int read() throws IOException { return inputContent.read(); } }); when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType()); Helper.parseRequest(request); }
From source file:com.voa.weixin.task.UpdateFileTask.java
@Override public void run() { logger.debug("updatefile url :" + this.url); generateUrl();/*ww w .ja va 2 s . co m*/ PostMethod filePost = new PostMethod(url); try { Part[] parts = { new FilePart(updateFile.getName(), updateFile) }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); WeixinResult result = new WeixinResult(); if (status == 200) { String responseStr = filePost.getResponseBodyAsString(); logger.debug(responseStr); result.setJson(responseStr); } else { result.setErrMsg("uplaod file weixin request error , http status : " + status); } callbackWork(result); } catch (Exception e) { e.printStackTrace(LogUtil.getErrorStream(logger)); throw new WorkException("update file error.", e); } finally { filePost.releaseConnection(); } }
From source file:mercury.UploadController.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); try {/*from w w w . ja v a 2 s . c om*/ List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String targetUrl = Config.getConfigProperty(ConfigurationEnum.DIGITAL_MEDIA); if (StringUtils.isBlank(targetUrl)) { targetUrl = request.getRequestURL().toString(); targetUrl = targetUrl.substring(0, targetUrl.lastIndexOf('/')); } targetUrl += "/DigitalMediaController"; PostMethod filePost = new PostMethod(targetUrl); filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); UploadPartSource src = new UploadPartSource(item.getName(), item.getSize(), item.getInputStream()); Part[] parts = new Part[1]; parts[0] = new FilePart(item.getName(), src, item.getContentType(), null); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { String data = filePost.getResponseBodyAsString(); JSONObject json = new JSONObject(data); if (json.has("id")) { JSONObject responseJson = new JSONObject(); responseJson.put("success", true); responseJson.put("id", json.getString("id")); responseJson.put("uri", targetUrl + "?id=" + json.getString("id")); response.getWriter().write(responseJson.toString()); } } filePost.releaseConnection(); return; } } } catch (FileUploadException e) { e.printStackTrace(); } catch (JSONException je) { je.printStackTrace(); } } response.getWriter().write("{success: false}"); }
From source file:com.linkedin.pinot.common.utils.SchemaUtils.java
/** * Given host, port and schema, send a http POST request to upload the {@link Schema}. * * @return <code>true</code> on success. * <P><code>false</code> on failure. *///ww w.jav a 2 s . com public static boolean postSchema(@Nonnull String host, int port, @Nonnull Schema schema) { Preconditions.checkNotNull(host); Preconditions.checkNotNull(schema); try { URL url = new URL("http", host, port, "/schemas"); PostMethod httpPost = new PostMethod(url.toString()); try { Part[] parts = { new StringPart(schema.getSchemaName(), schema.toString()) }; MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, new HttpMethodParams()); httpPost.setRequestEntity(requestEntity); int responseCode = HTTP_CLIENT.executeMethod(httpPost); if (responseCode >= 400) { String response = httpPost.getResponseBodyAsString(); LOGGER.warn("Got error response code: {}, response: {}", responseCode, response); return false; } return true; } finally { httpPost.releaseConnection(); } } catch (Exception e) { LOGGER.error("Caught exception while posting the schema: {} to host: {}, port: {}", schema.getSchemaName(), host, port, e); return false; } }
From source file:net.sourceforge.jwbf.actions.mw.editing.FileUpload.java
/** * /*from ww w. j a v a 2 s . co m*/ * @param a the * @param tab internal value set * @param login a * @throws ActionException on problems with file */ public FileUpload(final SimpleFile a, final Hashtable<String, String> tab, LoginData login) throws ActionException { if (!a.getFile().isFile() || !a.getFile().canRead()) { throw new ActionException("no such file " + a.getFile()); } String uS = ""; // try { uS = "/Spezial:Hochladen"; uS = "/index.php?title=Special:Upload"; // uS = "/index.php?title=" + URLEncoder.encode("Spezial:Hochladen", // MediaWikiBot.CHARSET); // + "&action=submit"; // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } try { LOG.info("WRITE: " + a.getLabel()); PostMethod post = new PostMethod(uS); Part[] parts; if (a.getText().isEmpty()) { parts = new Part[] { new StringPart("wpDestFile", a.getLabel()), new StringPart("wpIgnoreWarning", "true"), new StringPart("wpSourceType", "file"), new StringPart("wpUpload", "Upload file"), // new StringPart("wpUploadDescription", "false"), // new StringPart("wpWatchthis", "false"), new FilePart("wpUploadFile", a.getFile()) // new FilePart( f.getName(), f) }; } else { parts = new Part[] { new StringPart("wpDestFile", a.getLabel()), new StringPart("wpIgnoreWarning", "true"), new StringPart("wpSourceType", "file"), new StringPart("wpUpload", "Upload file"), // new StringPart("wpUploadDescription", "false"), // new StringPart("wpWatchthis", "false"), new FilePart("wpUploadFile", a.getFile()), // new FilePart( f.getName(), f) new StringPart("wpUploadDescription", a.getText()) }; } post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); // int statusCode = hc.executeMethod(post); // log(statusCode); // log(Arrays.asList(post.getResponseHeaders())); // // String res = post.getResponseBodyAsString(); // LOG.debug(res); // post.releaseConnection(); // pm.setRequestBody(new NameValuePair[] { action, wpStarttime, // wpEditToken, wpEdittime, wpTextbox, wpSummary, wpMinoredit }); msgs.add(post); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }