List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity
public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams)
From source file:com.apatar.ui.JSubmitHelpDialog.java
private void addListeners() { sendButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { PostMethod filePost = new PostMethod(getUrl()); try { if (!CoreUtils.validEmail(emailField.getText())) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "E-mail address is invalid! Please, write a valid e-mail."); return; }/* ww w . j a v a 2 s . com*/ List<File> targetFiles = getAttachFile(); List<FilePart> fParts = new ArrayList<FilePart>(); int i = 1; for (File file : targetFiles) { try { fParts.add(new FilePart("file" + i, file)); i++; } catch (java.io.FileNotFoundException ef) { } } int size = fParts.size() + 4; Part[] parts = new Part[size]; parts[0] = new StringPart("BugInformation", text.getText()); parts[1] = new StringPart("FirstName", firstNameField.getText()); parts[2] = new StringPart("LastName", lastNameField.getText()); parts[3] = new StringPart("Email", emailField.getText()); i = 4; for (FilePart fp : fParts) parts[i++] = fp; 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) JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Upload failed, response=" + HttpStatus.getStatusText(status)); else { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Your message has been sent. Thank you!"); dispose(); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } } }); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); }
From source file:fr.opensagres.xdocreport.remoting.reporting.server.ReportingServiceWithHttpClientTestCase.java
@Test public void generateReportandConvertToPDF() throws Exception { PostMethod post = new PostMethod("http://localhost:" + PORT + "/report"); String ct = "multipart/mixed"; post.setRequestHeader("Content-Type", ct); Part[] parts = new Part[7]; String fileName = "DocxProjectWithVelocityAndImageList.docx"; // 1) Param [templateDocument]: input stream of the docx, odt... parts[0] = new FilePart("templateDocument", new File(root, fileName), "application/vnd.oasis.opendocument.text", "UTF-8"); // 2) Param [templateEngineKind]: Velocity or Freemarker parts[1] = new StringPart("templateEngineKind", "Velocity"); // 3) Param [metadata]: XML fields metadata // XML fields metadata // ex:<?xml version="1.0" encoding="UTF-8" standalone="yes"?><fields templateEngineKind="" // ><description><![CDATA[]]></description><field name="developers.Name" list="true" imageName="" // syntaxKind=""><description><![CDATA[]]></description></field><field name="developers.LastName" list="true" // imageName="" syntaxKind=""><description><![CDATA[]]></description></field><field name="developers.Mail" // list="true" imageName="" syntaxKind=""><description><![CDATA[]]></description></field></fields> FieldsMetadata metadata = new FieldsMetadata(); // manage lazy loop for the table which display list of developers in the docx metadata.addFieldAsList("developers.Name"); metadata.addFieldAsList("developers.LastName"); metadata.addFieldAsList("developers.Mail"); StringWriter xml = new StringWriter(); metadata.saveXML(xml);/* ww w. j ava 2 s .co m*/ parts[2] = new StringPart("metadata", xml.toString()); // 4) Param [data]: JSON data which must be merged with the docx template String jsonData = "{" + "project:" + "{Name:'XDocReport', URL:'http://code.google.com/p/xdocreport'}, " + "developers:" + "[" + "{Name: 'ZERR', Mail: 'angelo.zerr@gmail.com',LastName: 'Angelo'}," + "{Name: 'Leclercq', Mail: 'pascal.leclercq@gmail.com',LastName: 'Pascal'}" + "]" + "}"; parts[3] = new StringPart("data", jsonData); // 4) Param [dataType]: data type parts[4] = new StringPart("dataType", "json"); // 5) Param [outFileName]: output file name parts[5] = new StringPart("outFileName", "report.pdf"); parts[6] = new StringPart("outFormat", "PDF"); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); HttpClient httpclient = new HttpClient(); try { int result = httpclient.executeMethod(post); Assert.assertEquals(200, result); Assert.assertEquals("attachment; filename=\"report.pdf\"", post.getResponseHeader("Content-Disposition").getValue()); byte[] convertedDocument = post.getResponseBody(); Assert.assertNotNull(convertedDocument); File outFile = new File("target/report.pdf"); outFile.getParentFile().mkdirs(); IOUtils.copy(new ByteArrayInputStream(convertedDocument), new FileOutputStream(outFile)); } finally { post.releaseConnection(); } }
From source file:com.thoughtworks.twist.mingle.core.MingleClient.java
public void attachFile(String taskId, String comment, String description, AbstractTaskAttachmentSource source, String filename, IProgressMonitor monitor) { PostMethod post = new PostMethod(attachmentUrl(taskId)); List<PartBase> parts = new ArrayList<PartBase>(); String fileName = source.getName(); parts.add(new FilePart("attachments[0]", new AttachmentPartSource(source))); post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[1]), post.getParams())); try {//from w w w .jav a 2s.co m int executeMethod = getClient().executeMethod(post); String responseBodyAsString = post.getResponseBodyAsString(); System.out.println(); } catch (HttpException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { post.releaseConnection(); } }
From source file:com.ziaconsulting.zoho.EditorController.java
@Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { Match match = req.getServiceMatch(); Map<String, String> vars = match.getTemplateVars(); NodeRef theNodeRef = new NodeRef(vars.get("store_type"), vars.get("store_id"), vars.get("id")); String fileName = serviceRegistry.getNodeService().getProperty(theNodeRef, ContentModel.PROP_NAME) .toString();/* ww w .j a v a2s . c o m*/ String protocol = ssl ? "https" : "http"; String extension; if (fileName.lastIndexOf('.') != -1) { extension = fileName.substring(fileName.lastIndexOf('.') + 1); } else { String contentMime = serviceRegistry.getContentService() .getReader(theNodeRef, ContentModel.PROP_CONTENT).getMimetype(); extension = serviceRegistry.getMimetypeService().getExtensionsByMimetype().get(contentMime); // Attach this extension to the filename fileName += "." + extension; log.debug("Extension not found, using mimetype " + contentMime + " to guess the extension file name is now " + fileName); } String zohoUrl = ""; if (Arrays.binarySearch(zohoDocFileExtensions, extension) >= 0) { zohoUrl = writerUrl; } else if (Arrays.binarySearch(zohoXlsFileExtensions, extension) >= 0) { zohoUrl = sheetUrl; } else if (Arrays.binarySearch(zohoPptFileExtensions, extension) >= 0) { zohoUrl = showUrl; } else { log.info("Invalid extension " + extension); return getErrorMap("Invalid extension"); } // Create multipart form for post List<Part> parts = new ArrayList<Part>(); String output = ""; if (vars.get("mode").equals("edit")) { output = "url"; parts.add(new StringPart("mode", "collabedit")); } else if (vars.get("mode").equals("view")) { output = "viewurl"; parts.add(new StringPart("mode", "view")); } String docIdBase = vars.get("store_type") + vars.get("store_id") + vars.get("id"); parts.add(new StringPart("documentid", generateDocumentId(docIdBase))); String id = theNodeRef.toString() + "#" + serviceRegistry.getAuthenticationService().getCurrentTicket(); parts.add(new StringPart("id", id)); parts.add(new StringPart("format", extension)); parts.add(new StringPart("filename", fileName)); parts.add(new StringPart("username", serviceRegistry.getAuthenticationService().getCurrentUserName())); parts.add(new StringPart("skey", skey)); if (useRemoteAgent) { parts.add(new StringPart("agentname", remoteAgentName)); } else { String saveUrl; saveUrl = protocol + "://" + this.saveUrl + "/alfresco/s/zohosave"; parts.add(new StringPart("saveurl", saveUrl)); } ContentReader cr = serviceRegistry.getContentService().getReader(theNodeRef, ContentModel.PROP_CONTENT); if (!(cr instanceof FileContentReader)) { log.error("The content reader was not a FileContentReader"); return getErrorMap("Error"); } PartSource src = null; try { src = new FilePartSource(fileName, ((FileContentReader) cr).getFile()); } catch (FileNotFoundException e) { e.printStackTrace(); log.error("The content did not exist."); return getErrorMap("Error"); } parts.add(new FilePart("content", src, cr.getMimetype(), null)); HttpClient client = new HttpClient(); String zohoFormUrl = protocol + "://" + zohoUrl + "/remotedoc.im?" + "apikey=" + apiKey + "&output=" + output; PostMethod httppost = new PostMethod(zohoFormUrl); httppost.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), httppost.getParams())); Map<String, Object> returnMap = getReturnMap(); String retStr = ""; int zohoStatus = 0; try { zohoStatus = client.executeMethod(httppost); retStr = httppost.getResponseBodyAsString(); } catch (HttpException he) { log.error("Error", he); returnMap = getErrorMap("Error"); } catch (IOException io) { io.printStackTrace(); log.error("Error", io); returnMap = getErrorMap("Error"); } if (zohoStatus == 200) { Map<String, String> parsedResponse = parseResponse(retStr); if (parsedResponse.containsKey("RESULT") && parsedResponse.get("RESULT").equals("TRUE")) { returnMap.put("zohourl", parsedResponse.get("URL")); } else if (parsedResponse.containsKey("RESULT") && parsedResponse.get("RESULT").equals("FALSE")) { returnMap = getErrorMap(parsedResponse.get("ERROR")); } } else { returnMap = getErrorMap("Remote server did not respond"); } return returnMap; }
From source file:hk.hku.cecid.corvus.http.PartnershipSender.java
/** * [@EVENT] This method is invoked when the sender is required to create a HTTP Request from configuration. * <br/><br/>//from w w w . j a v a2 s . c om * It generates a multi-part content embedded in the HTTP POST request. The multi-part content * contains all partnership data with the parameter name retrieved from the partnership mapping. * {@link #getPartnershipMapping()}. Also the type of partnership operation is appended * at the end of multi-part with parameter name equal to 'request_action' and it's value * is extracted thru {@link #getPartnershipOperationMapping()}. */ protected HttpMethod onCreateRequest() throws Exception { // Validate main parameter. Map data = ((KVPairData) this.properties).getProperties(); Map data2webFormName = this.getPartnershipMapping(); if (data2webFormName == null) throw new NullPointerException("Missing partnership mapping for creating HTTP request"); // Create the HTTP POST method targeted to service end-point. PostMethod post = new PostMethod(this.getServiceEndPoint().toExternalForm()); List parts = new ArrayList(); // An array for multi-part; /* * For each data key in the partnership data, create a String multi-part * with the request parameter name equal to the mapping from the data key. * * For the field like verification / encryption certificates, it creates * a byte array multi-part source. */ Iterator itr = data2webFormName.entrySet().iterator(); Map.Entry e; // an entry representing the partnership data to web form name mapping. String formParamName; // a temporary pointer pointing to the value in the entry. Object dataValue; // a temporary pointer pointing to the value in the partnership data. Part newPart; // a temporary pointer pointing to a multi-part part. while (itr.hasNext()) { e = (Map.Entry) itr.next(); formParamName = (String) e.getValue(); // Add new part if the mapped key is not null. if (e.getValue() != null) { dataValue = data.get(e.getKey()); if (dataValue == null) // Use empty string when the key is not filled. dataValue = ""; if (dataValue instanceof String) { // Create literal part newPart = new StringPart(formParamName, (String) dataValue); } else if (dataValue instanceof byte[]) { // Create streaming multi-part PartSource source = new ByteArrayPartSource((String) e.getKey(), (byte[]) dataValue); newPart = new FilePart(formParamName, source); } else if (dataValue instanceof Boolean) { newPart = new StringPart(formParamName, String.valueOf((Boolean) dataValue)); } else { newPart = new StringPart(formParamName, dataValue.toString()); } // Add the new part. parts.add(newPart); } } Map partnershipOpMap = this.getPartnershipOperationMapping(); /* Add HTTP request action to the web form parameter. */ parts.add(new StringPart("request_action", (String) partnershipOpMap.get(new Integer(this.pOp)))); MultipartRequestEntity multipartRequest = new MultipartRequestEntity((Part[]) parts.toArray(new Part[] {}), post.getParams()); post.setRequestEntity(multipartRequest); return post; }
From source file:com.sun.faban.harness.util.CLI.java
private void doPostSubmit(String master, String user, String password, ArrayList<String> argList) throws IOException { String url = master + argList.get(0) + '/' + argList.get(1) + '/' + argList.get(2); ArrayList<Part> params = new ArrayList<Part>(); if (user != null) params.add(new StringPart("sun", user)); if (password != null) params.add(new StringPart("sp", password)); int submitCount = 0; for (int i = 3; i < argList.size(); i++) { File configFile = new File(argList.get(i)); if (configFile.isFile()) { params.add(new FilePart("configfile", configFile)); ++submitCount;/*from w w w . j ava 2 s . co m*/ } else { System.err.println("File " + argList.get(i) + " not found."); } } if (submitCount == 0) { throw new IOException("No run submitted!"); } Part[] parts = new Part[params.size()]; parts = params.toArray(parts); PostMethod post = new PostMethod(url); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); makeRequest(post); }
From source file:com.groupon.odo.HttpUtilities.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data * as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a * multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the multipart * POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} *///from w ww . j a v a 2s. c om @SuppressWarnings("unchecked") public static void handleMultipartPost(EntityEnclosingMethod postMethodProxyRequest, HttpServletRequest httpServletRequest, DiskFileItemFactory diskFileItemFactory) throws ServletException { // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string // part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[listParts.size()]), postMethodProxyRequest.getParams()); postMethodProxyRequest.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:com.linkedin.pinot.controller.helix.ControllerTest.java
public static PostMethod sendMultipartPostRequest(String url, String body) throws IOException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url); // our handlers ignore key...so we can put anything here Part[] parts = { new StringPart("body", body) }; postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); httpClient.executeMethod(postMethod); return postMethod; }
From source file:com.twinsoft.convertigo.engine.util.RemoteAdmin.java
public void deployArchive(File archiveFile, boolean bAssembleXsl) throws RemoteAdminException { String deployServiceURL = (bHttps ? "https" : "http") + "://" + serverBaseUrl + "/admin/services/projects.Deploy?bAssembleXsl=" + bAssembleXsl; PostMethod deployMethod = null;/*w ww. j a v a 2s. com*/ Protocol myhttps = null; try { if (bHttps && bTrustAllCertificates) { ProtocolSocketFactory socketFactory = MySSLSocketFactory.getSSLSocketFactory(null, null, null, null, true); myhttps = new Protocol("https", socketFactory, serverPort); Protocol.registerProtocol("https", myhttps); hostConfiguration = httpClient.getHostConfiguration(); hostConfiguration.setHost(host, serverPort, myhttps); httpClient.setHostConfiguration(hostConfiguration); } deployMethod = new PostMethod(deployServiceURL); Part[] parts = { new FilePart(archiveFile.getName(), archiveFile) }; deployMethod.setRequestEntity(new MultipartRequestEntity(parts, deployMethod.getParams())); int returnCode = httpClient.executeMethod(deployMethod); String httpResponse = deployMethod.getResponseBodyAsString(); if (returnCode == HttpStatus.SC_OK) { Document domResponse; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); domResponse = parser.parse(new InputSource(new StringReader(httpResponse))); domResponse.normalize(); NodeList nodeList = domResponse.getElementsByTagName("error"); if (nodeList.getLength() != 0) { Element errorNode = (Element) nodeList.item(0); Element errorMessage = (Element) errorNode.getElementsByTagName("message").item(0); Element exceptionName = (Element) errorNode.getElementsByTagName("exception").item(0); Element stackTrace = (Element) errorNode.getElementsByTagName("stacktrace").item(0); if (errorMessage != null) { throw new RemoteAdminException(errorMessage.getTextContent(), exceptionName.getTextContent(), stackTrace.getTextContent()); } else { throw new RemoteAdminException( "An unexpected error has occured during the Convertigo project deployment: \n" + "Body content: \n\n" + XMLUtils.prettyPrintDOMWithEncoding(domResponse, "UTF-8")); } } } catch (ParserConfigurationException e) { throw new RemoteAdminException("Unable to parse the Convertigo server response: \n" + e.getMessage() + ".\n" + "Received response: " + httpResponse); } catch (IOException e) { throw new RemoteAdminException( "An unexpected error has occured during the Convertigo project deployment.\n" + "(IOException) " + e.getMessage() + "\n" + "Received response: " + httpResponse, e); } catch (SAXException e) { throw new RemoteAdminException("Unable to parse the Convertigo server response: " + e.getMessage() + ".\n" + "Received response: " + httpResponse); } } else { decodeResponseError(httpResponse); } } catch (HttpException e) { throw new RemoteAdminException( "An unexpected error has occured during the Convertigo project deployment.\n" + "Cause: " + e.getMessage(), e); } catch (IOException e) { throw new RemoteAdminException( "Unable to reach the Convertigo server: \n" + "(IOException) " + e.getMessage(), e); } catch (Exception e) { throw new RemoteAdminException( "Unable to reach the Convertigo server: \n" + "(Exception) " + e.getMessage(), e); } finally { Protocol.unregisterProtocol("https"); if (deployMethod != null) deployMethod.releaseConnection(); } }
From source file:com.mobilefirst.fiberlink.WebServiceRequest.java
/** * Description: Create the Request Object * @param authToken: required token passed through from initial Authenticator() request * @param baseURL: Initial base URL of host and port * @param webServiceName: Context root for particular request * @param methodType: Integer to say get or post request * @param billingId: billing ID to populate into the request * @param parametersObjectList: Map containing option parameters, headers and multi-part object * @throws Exception// w w w . j a v a 2 s.c om */ public void createRequest(String authToken, String baseURL, String webServiceName, int methodType, String billingId, Hashtable<String, Object> parametersObjectList, String... strings) { try { String apiVersion; if (strings.length > 0) { if (strings[0].contentEquals("not-found")) { apiVersion = "1.0"; } else { apiVersion = strings[0]; } } else { apiVersion = "1.0"; } String uri = baseURL + webServiceName.replace("api-version", apiVersion) + billingId; System.out.println(">>>Generating Request URL"); System.out.println("Base URL :: " + uri); initializeRequestHeadersAndParameters(parametersObjectList); switch (methodType) { case 0: // Setting PARAMETERS if any // this must be before setting the getMethod with URI // otherwise request will be created with base URI and no parameters if (0 != parameters.size()) { uri = formulateGetURI(uri, parameters); } getMethod = new GetMethod(uri); //Setting Required Authorization Header System.out.println(">>>Generating GET Request"); getMethod.addRequestHeader("Authorization", "MaaS token=\"" + authToken + "\""); // Setting HEADERS if any if (0 != headers.size()) { Enumeration<String> keys = headers.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); getMethod.addRequestHeader(key, headers.get(key)); } } System.out.println(">>>Sending GET Request"); sendRequest(getMethod, ""); break; case 1: postMethod = new PostMethod(uri); //Setting Required Authorization Header System.out.println(">>>Generating POST Request"); postMethod.addRequestHeader("Authorization", "MaaS token=\"" + authToken + "\""); // Setting HEADERS if any if (0 != headers.size()) { Enumeration<String> keys = headers.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); postMethod.addRequestHeader(key, headers.get(key)); } } // Setting PARAMETERS if any if (0 != parameters.size()) { postMethod.setParams(setMethodParams(postMethod, parameters)); } //START special case //If you need to send request body without any encoding or name pair values : like ws which involves bulk like GetCoreAttributesBulk. if (parametersObjectList.containsKey("body")) { org.apache.commons.httpclient.methods.StringRequestEntity sre; @SuppressWarnings("unchecked") Hashtable<String, String> a = (Hashtable<String, String>) parametersObjectList.get("body"); sre = new StringRequestEntity(a.get("payload"), "application/xml", "UTF-8"); postMethod.setRequestEntity(sre); } //END of the special case //Setting multipart body post if required. if (null != parts) { postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); } System.out.println(">>>Sending POST Request"); sendRequest(postMethod, ""); break; default: break; } } catch (Exception e) { } }