List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity
public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams)
From source file:fr.opensagres.xdocreport.remoting.reporting.server.ReportingServiceWithHttpClientTestCase.java
@Test public void generateReport() throws Exception { PostMethod post = new PostMethod("http://localhost:" + PORT + "/report"); String ct = "multipart/mixed"; post.setRequestHeader("Content-Type", ct); Part[] parts = new Part[6]; 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);//from w ww. ja va 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.docx"); 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.docx\"", post.getResponseHeader("Content-Disposition").getValue()); byte[] convertedDocument = post.getResponseBody(); Assert.assertNotNull(convertedDocument); File outFile = new File("target/report.docx"); outFile.getParentFile().mkdirs(); IOUtils.copy(new ByteArrayInputStream(convertedDocument), new FileOutputStream(outFile)); } finally { post.releaseConnection(); } }
From source file:hk.hku.cecid.corvus.http.HttpSenderUnitTest.java
/** Test whether the HTTP sender able to send the HTTP header with multi-part to our monitor successfully. */ public void testSendWithMultipart() throws Exception { this.target = new HttpSender(this.testClassLogger, new KVPairData(0)) { public HttpMethod onCreateRequest() throws Exception { PostMethod method = new PostMethod("http://localhost:1999"); Part[] parts = { new StringPart("testparamName", "testparamValue") }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); return method; }/*from ww w. jav a2s.c o m*/ }; this.assertSend(); }
From source file:com.jmeter.alfresco.utils.HttpUtils.java
/** * Document upload.//w ww . java 2s. c om * * @param docFileObj the doc file obj * @param authTicket the auth ticket * @param uploadURI the upload uri * @param siteID the site id * @param uploadDir the upload dir * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public String documentUpload(final File docFileObj, final String authTicket, final String uploadURI, final String siteID, final String uploadDir) throws IOException { String uploadResponse = Constants.EMPTY; PostMethod postRequest = null; try { final String uploadURL = getFileUploadURL(uploadURI, authTicket); LOG.info("documentUpload() | Upload URL: " + uploadURL); final HttpClient httpClient = new HttpClient(); postRequest = new PostMethod(uploadURL); final String mimeType = getMimeType(docFileObj); final String docName = docFileObj.getName(); LOG.debug("documentUpload() | Uploading document: " + docName + " , content-type: " + mimeType); final Part[] parts = { new FilePart("filedata", docName, docFileObj, mimeType, null), new StringPart("filename", docName), new StringPart("overwrite", "true"), new StringPart("siteid", siteID), new StringPart("containerid", ConfigReader.getProperty(Constants.CONTAINER_ID)), new StringPart("uploaddirectory", uploadDir) }; postRequest.setRequestEntity(new MultipartRequestEntity(parts, postRequest.getParams())); final int statusCode = httpClient.executeMethod(postRequest); uploadResponse = postRequest.getResponseBodyAsString(); LOG.info("documentUpload() | Upload status: " + statusCode); LOG.debug("documentUpload() | Upload response: " + uploadResponse); } finally { if (postRequest != null) { //releaseConnection http connection postRequest.releaseConnection(); } } return uploadResponse; }
From source file:jp.co.cyberagent.jenkins.plugins.AndroidAppZonePublisher.java
@Override public boolean perform(final AbstractBuild build, final Launcher launcher, final BuildListener listener) { StringBuilder changeLog = new StringBuilder(); for (Object changeObject : build.getChangeSet().getItems()) { ChangeLogSet.Entry change = (ChangeLogSet.Entry) changeObject; if (changeLog.length() > 0) { changeLog.append("\n"); }/*ww w . j a v a 2 s. c o m*/ changeLog.append(change.getMsg() + " (" + change.getAuthor().getDisplayName() + ")"); } String server = getDescriptor().getServer(); if (server == null || server.length() == 0) { listener.getLogger().println(TAG + "AppZone server not set. Please set in global config! Aborting."); return false; } List<FilePath> files = getPossibleAppFiles(build, listener); if (files.isEmpty()) { listener.getLogger().println(TAG + "No file to publish found. Skip."); return true; } Iterator<FilePath> fileIterator = files.iterator(); while (fileIterator.hasNext()) { try { FilePath file = fileIterator.next(); String fileName = file.getName(); DeployStrategy deploy; listener.getLogger().println(TAG + "File: " + fileName); if (fileName.endsWith(".apk")) { deploy = new DeployStrategyAndroid(server, id, tag, prependNameToTag, file, build, listener); } else if (fileName.endsWith(".ipa")) { deploy = new DeployStrategyIOs(server, id, tag, prependNameToTag, file, build, listener); } else { return false; } deploy.setApiKey(getDescriptor().getApikey()); deploy.setChangeLog(changeLog.toString()); listener.getLogger().println(TAG + "Version: " + deploy.getVersion()); listener.getLogger().println(TAG + "Publishing to: " + deploy.getUrl()); setUpSsl(); HttpClient httpclient = new HttpClient(); PostMethod filePost = new PostMethod(deploy.getUrl()); List<Part> parts = deploy.getParts(); filePost.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), filePost.getParams())); httpclient.executeMethod(filePost); int statusCode = filePost.getStatusCode(); if (statusCode < 200 || statusCode > 299) { String body = filePost.getResponseBodyAsString(); listener.getLogger().println(TAG + "Response (" + statusCode + "):" + body); return false; } } catch (IOException e) { listener.getLogger().print(e.getMessage()); return false; } } return true; }
From source file:edu.virginia.speclab.juxta.author.view.export.WebServiceClient.java
/** * Send a cancel request to the webservice to abort the current * export operation./*from w ww . j a v a 2 s.c om*/ * @throws IOException */ public void cancelExport(String taskId) throws IOException { PostMethod post = new PostMethod(this.baseUrl + "/import/" + taskId + "/cancel"); Part[] parts = { new StringPart("token", this.authToken) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); execRequest(post); post.releaseConnection(); }
From source file:com.zimbra.qa.unittest.TestFileUpload.java
@Test public void testAdminUploadWithCsrfInHeader() throws Exception { SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl()); com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest( LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value()); req.setCsrfSupported(true);//from w ww . j a v a 2 s . c o m Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory())); com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response); String authToken = authResp.getAuthToken(); String csrfToken = authResp.getCsrfToken(); int port = 7071; try { port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0); } catch (ServiceException e) { ZimbraLog.test.error("Unable to get admin SOAP port", e); } String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL; PostMethod post = new PostMethod(Url); FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes())); String contentType = "application/x-msdownload"; part.setContentType(contentType); HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); HttpState state = new HttpState(); state.addCookie(new org.apache.commons.httpclient.Cookie("localhost", ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false)); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.setState(state); post.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, post.getParams())); post.addRequestHeader(Constants.CSRF_TOKEN, csrfToken); int statusCode = HttpClientUtil.executeMethod(client, post); assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode); String resp = post.getResponseBodyAsString(); assertNotNull("Response should not be empty", resp); assertTrue("Incorrect HTML response", resp.contains(RESP_STR)); }
From source file:com.zb.app.external.wechat.service.WeixinService.java
public void upload(File file, String type) { StringBuilder sb = new StringBuilder(400); sb.append("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="); sb.append(getAccessToken());/*from w w w .j av a 2 s .co m*/ sb.append("&type=").append(type); PostMethod postMethod = new PostMethod(sb.toString()); try { // FilePart? FilePart fp = new FilePart("filedata", file); Part[] parts = { fp }; // MIMEhttpclientMulitPartRequestEntity MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams()); postMethod.setRequestEntity(mre); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// int status = client.executeMethod(postMethod); if (status == HttpStatus.SC_OK) { logger.error(postMethod.getResponseBodyAsString()); } else { logger.error("fail"); } byte[] responseBody = postMethod.getResponseBody(); String result = new String(responseBody, "utf-8"); logger.error("result : " + result); } catch (Exception e) { e.printStackTrace(); } finally { // postMethod.releaseConnection(); } }
From source file:com.bakhtiyor.android.tumblr.TumblrService.java
private void uploadPhoto(String email, String password, String caption, boolean isPrivate, String filename) { try {//from w w w. j a v a2 s.c om File file = new File(filename); final HttpClient httpClient = new org.apache.commons.httpclient.HttpClient(); final PostMethod multipartPost = new PostMethod(API_URL); Part[] parts = { new StringPart(FIELD_EMAIL, email), new StringPart(FIELD_PASSWORD, password), new StringPart(FIELD_TYPE, "photo"), new StringPart("generator", GENERATOR), new StringPart(FIELD_CAPTION, caption), new StringPart(FIELD_PRIVATE, isPrivate ? "1" : "0"), new FilePart("data", file) }; multipartPost.setRequestEntity(new MultipartRequestEntity(parts, multipartPost.getParams())); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000); int id = new Random().nextInt(); showUploadingNotification(id); int status = httpClient.executeMethod(multipartPost); clearNotification(id); if (status == 201) { showResultNotification("Successful Uploaded"); } else { showResultNotification("Error occured"); } } catch (Throwable e) { Log.e(TAG, e.getMessage(), e); } }
From source file:com.boyuanitsm.pay.alipay.util.httpClient.HttpProtocolHandler.java
/** * Http//from w ww. j a v a 2 s. c om * * @param request ? * @param strParaFileName ??? * @param strFilePath * @return * @throws HttpException, IOException */ public HttpResponse execute(HttpRequest request, String strParaFileName, String strFilePath) throws HttpException, IOException { HttpClient httpclient = new HttpClient(connectionManager); // int connectionTimeout = defaultConnectionTimeout; if (request.getConnectionTimeout() > 0) { connectionTimeout = request.getConnectionTimeout(); } httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // int soTimeout = defaultSoTimeout; if (request.getTimeout() > 0) { soTimeout = request.getTimeout(); } httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout); // ConnectionManagerconnection httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout); String charset = request.getCharset(); charset = charset == null ? DEFAULT_CHARSET : charset; HttpMethod method = null; //get?? if (request.getMethod().equals(HttpRequest.METHOD_GET)) { method = new GetMethod(request.getUrl()); method.getParams().setCredentialCharset(charset); // parseNotifyConfig??GETrequestQueryString method.setQueryString(request.getQueryString()); } else if (strParaFileName.equals("") && strFilePath.equals("")) { //post?? method = new PostMethod(request.getUrl()); ((PostMethod) method).addParameters(request.getParameters()); method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset=" + charset); } else { //post? method = new PostMethod(request.getUrl()); List<Part> parts = new ArrayList<Part>(); for (int i = 0; i < request.getParameters().length; i++) { parts.add(new StringPart(request.getParameters()[i].getName(), request.getParameters()[i].getValue(), charset)); } //?strParaFileName??? parts.add(new FilePart(strParaFileName, new FilePartSource(new File(strFilePath)))); // ((PostMethod) method).setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams())); } // Http HeaderUser-Agent method.addRequestHeader("User-Agent", "Mozilla/4.0"); HttpResponse response = new HttpResponse(); try { httpclient.executeMethod(method); if (request.getResultType().equals(HttpResultType.STRING)) { response.setStringResult(method.getResponseBodyAsString()); } else if (request.getResultType().equals(HttpResultType.BYTES)) { response.setByteResult(method.getResponseBody()); } response.setResponseHeaders(method.getResponseHeaders()); } catch (UnknownHostException ex) { return null; } catch (IOException ex) { return null; } catch (Exception ex) { return null; } finally { method.releaseConnection(); } return response; }
From source file:com.cognifide.maven.plugins.crx.CrxPackageAbstractMojo.java
/** * Performs post request to given URL with given parameters provided as a part lists. * /*from w ww . java 2 s .c om*/ * @param targetURL Place where post action should be submitted * @param partList Parameters of post action * @return Response body * @throws MojoExecutionException */ protected String post(String targetURL, List<Part> partList) throws MojoExecutionException { PostMethod postMethod = new PostMethod(targetURL); try { Part[] parts = partList.toArray(new Part[partList.size()]); postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); int status = getHttpClient().executeMethod(postMethod); if (status == HttpStatus.SC_OK) { return IOUtils.toString(postMethod.getResponseBodyAsStream()); } else { getLog().warn(postMethod.getResponseBodyAsString()); throw new MojoExecutionException("Request to the repository failed, cause: " + HttpStatus.getStatusText(status) + " (check URL, user and password)"); } } catch (IOException ex) { throw new MojoExecutionException("Request to the repository failed, cause: " + ex.getMessage(), ex); } finally { postMethod.releaseConnection(); } }