List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same content POST * data (JSON, XML, etc.) as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are * configuring to send a standard POST request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} */// w w w. j a v a 2s.c o m private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws IOException, ServletException { StringBuilder content = new StringBuilder(); BufferedReader reader = httpServletRequest.getReader(); for (;;) { String line = reader.readLine(); if (line == null) break; content.append(line); } String contentType = httpServletRequest.getContentType(); String postContent = content.toString(); if (contentType.startsWith("text/x-gwt-rpc")) { String clientHost = httpServletRequest.getLocalName(); if (clientHost.equals("127.0.0.1")) { clientHost = "localhost"; } int clientPort = httpServletRequest.getLocalPort(); String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : ""); String serverUrl = stringProxyHost + ((intProxyPort != 80) ? ":" + intProxyPort : "") + httpServletRequest.getServletPath(); //debug("Replacing client (" + clientUrl + ") with server (" + serverUrl + ")"); postContent = postContent.replace(clientUrl, serverUrl); } String encoding = httpServletRequest.getCharacterEncoding(); debug("POST Content Type: " + contentType + " Encoding: " + encoding, "Content: " + postContent); StringRequestEntity entity; try { entity = new StringRequestEntity(postContent, contentType, encoding); } catch (UnsupportedEncodingException e) { throw new ServletException(e); } // Set the proxy request POST data postMethodProxyRequest.setRequestEntity(entity); }
From source file:com.liferay.portal.util.HttpImpl.java
protected void processPostMethod(PostMethod postMethod, List<Http.FilePart> fileParts, Map<String, String> parts) { if ((fileParts == null) || fileParts.isEmpty()) { if (parts != null) { for (Map.Entry<String, String> entry : parts.entrySet()) { String value = entry.getValue(); if (Validator.isNotNull(value)) { postMethod.addParameter(entry.getKey(), value); }/*from www. jav a 2 s.co m*/ } } } else { List<Part> partsList = new ArrayList<Part>(); if (parts != null) { for (Map.Entry<String, String> entry : parts.entrySet()) { String value = entry.getValue(); if (Validator.isNotNull(value)) { StringPart stringPart = new StringPart(entry.getKey(), value); partsList.add(stringPart); } } } for (Http.FilePart filePart : fileParts) { partsList.add(toCommonsFilePart(filePart)); } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( partsList.toArray(new Part[0]), postMethod.getParams()); postMethod.setRequestEntity(multipartRequestEntity); } }
From source file:com.borhan.client.BorhanClientBase.java
private PostMethod getPostMultiPartWithFiles(PostMethod method, BorhanParams kparams, BorhanFiles kfiles) { String boundary = "---------------------------" + System.currentTimeMillis(); List<Part> parts = new ArrayList<Part>(); parts.add(new StringPart(HttpMethodParams.MULTIPART_BOUNDARY, boundary)); parts.add(new StringPart("json", kparams.toString())); for (String key : kfiles.keySet()) { final BorhanFile kFile = kfiles.get(key); parts.add(new StringPart(key, "filename=" + kFile.getName())); if (kFile.getFile() != null) { // use the file File file = kFile.getFile(); try { parts.add(new FilePart(key, file)); } catch (FileNotFoundException e) { // TODO this sort of leaves the submission in a weird // state... -AZ if (logger.isEnabled()) logger.error("Exception while iterating over kfiles", e); }/*from w ww . j av a 2 s . co m*/ } else { // use the input stream PartSource fisPS = new PartSource() { public long getLength() { return kFile.getSize(); } public String getFileName() { return kFile.getName(); } public InputStream createInputStream() throws IOException { return kFile.getInputStream(); } }; parts.add(new FilePart(key, fisPS)); } } Part allParts[] = new Part[parts.size()]; allParts = parts.toArray(allParts); method.setRequestEntity(new MultipartRequestEntity(allParts, method.getParams())); return method; }
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);/*w ww . j a v a2 s. c o 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:com.kaltura.client.KalturaClientBase.java
private PostMethod getPostMultiPartWithFiles(PostMethod method, KalturaParams kparams, KalturaFiles kfiles) { String boundary = "---------------------------" + System.currentTimeMillis(); List<Part> parts = new ArrayList<Part>(); parts.add(new StringPart(HttpMethodParams.MULTIPART_BOUNDARY, boundary)); for (Entry<String, String> itr : kparams.entrySet()) { parts.add(new StringPart(itr.getKey(), itr.getValue())); }/*from w w w . j a va2s . c o m*/ for (String key : kfiles.keySet()) { final KalturaFile kFile = kfiles.get(key); parts.add(new StringPart(key, "filename=" + kFile.getName())); if (kFile.getFile() != null) { // use the file File file = kFile.getFile(); try { parts.add(new FilePart(key, file)); } catch (FileNotFoundException e) { // TODO this sort of leaves the submission in a weird state... -AZ if (logger.isEnabled()) logger.error("Exception while iterating over kfiles", e); } } else { // use the input stream PartSource fisPS = new PartSource() { public long getLength() { return kFile.getSize(); } public String getFileName() { return kFile.getName(); } public InputStream createInputStream() throws IOException { return kFile.getInputStream(); } }; parts.add(new FilePart(key, fisPS)); } } Part allParts[] = new Part[parts.size()]; allParts = parts.toArray(allParts); method.setRequestEntity(new MultipartRequestEntity(allParts, method.getParams())); return method; }
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);//w w w .ja v a2 s . c o 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.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java
/** * Sets up the given {@link PostMethod} to send the same multipart POST * data as was sent in the given {@link HttpServletRequest} * @param postMethodProxyRequest The {@link PostMethod} that we are * configuring to send a multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains * the mutlipart POST data to be sent via the {@link PostMethod} *///from www .j a v a 2 s . co m @SuppressWarnings("unchecked") private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws IOException { _log.debug("handleMultipartPost()"); // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY); // 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[] {}), 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(HttpConstants.STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new IOException(fileUploadException); } }
From source file:com.twelve.capital.external.feed.util.HttpImpl.java
protected void processPostMethod(PostMethod postMethod, List<Http.FilePart> fileParts, Map<String, String> parts) { if ((fileParts == null) || fileParts.isEmpty()) { if (parts != null) { for (Map.Entry<String, String> entry : parts.entrySet()) { String value = entry.getValue(); if (value != null) { postMethod.addParameter(entry.getKey(), value); }// w w w. j a v a 2 s .c o m } } } else { List<Part> partsList = new ArrayList<Part>(); if (parts != null) { for (Map.Entry<String, String> entry : parts.entrySet()) { String value = entry.getValue(); if (value != null) { StringPart stringPart = new StringPart(entry.getKey(), value); partsList.add(stringPart); } } } for (Http.FilePart filePart : fileParts) { partsList.add(toCommonsFilePart(filePart)); } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( partsList.toArray(new Part[partsList.size()]), postMethod.getParams()); postMethod.setRequestEntity(multipartRequestEntity); } }
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/>// ww w . j a v a2 s . co m * 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:net.sf.dsig.verify.OCSPHelper.java
/** * Check with OCSP protocol whether a certificate is valid * //from w w w .j a va2 s . c om * @param certificate an {@link X509Certificate} object * @return true if the certificate is valid; false otherwise * @throws NetworkAccessException when any network access issues occur * @throws VerificationException when an OCSP related error occurs */ public boolean isValid(X509Certificate certificate) throws NetworkAccessException, VerificationException { PostMethod post = null; try { CertificateID cid = new CertificateID(CertificateID.HASH_SHA1, caCertificate, certificate.getSerialNumber()); OCSPReqGenerator gen = new OCSPReqGenerator(); gen.addRequest(cid); // Nonce BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); Vector oids = new Vector(); Vector values = new Vector(); oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray()))); values.add(new X509Extension(false, new DEROctetString(new BigInteger("041063FAB2B54CF1ED014F9DF7C70AACE575", 16).toByteArray()))); gen.setRequestExtensions(new X509Extensions(oids, values)); // Requestor name - not really required, but added for completeness // gen.setRequestorName( // new GeneralName( // new X509Name( // certificate.getSubjectX500Principal().getName()))); logger.debug("Generating OCSP request" + "; serialNumber=" + certificate.getSerialNumber().toString(16) + ", nonce=" + nonce.toString(16) + ", caCertificate.subjectName=" + caCertificate.getSubjectX500Principal().getName()); // TODO Need to call the generate(...) method, that signs the // request. Which means, need to have a keypair for that, too OCSPReq req = gen.generate(); // First try finding the OCSP access location in the X.509 certificate String uriAsString = getOCSPAccessLocationUri(certificate); // If not found, try falling back to the default if (uriAsString == null) { uriAsString = defaultOcspAccessLocation; } // If still null, bail out if (uriAsString == null) { throw new ConfigurationException( "OCSP AccessLocation not found on certificate, and no default set"); } HostConfiguration config = getHostConfiguration(); post = new PostMethod(uriAsString); post.setRequestHeader("Content-Type", "application/ocsp-request"); post.setRequestHeader("Accept", "application/ocsp-response"); post.setRequestEntity(new ByteArrayRequestEntity(req.getEncoded())); getHttpClient().executeMethod(config, post); logger.debug("HTTP POST executed" + "; authorityInfoAccessUri=" + uriAsString + ", statusLine=" + post.getStatusLine()); if (post.getStatusCode() != HttpStatus.SC_OK) { throw new NetworkAccessException("HTTP GET failed; statusLine=" + post.getStatusLine()); } byte[] responseBodyBytes = post.getResponseBody(); OCSPResp ocspRes = new OCSPResp(responseBodyBytes); if (ocspRes.getStatus() != OCSPResponseStatus.SUCCESSFUL) { // One possible exception is the use of a wrong CA certificate throw new ConfigurationException("OCSP request failed; possibly wrong issuer/user certificate" + "; status=" + ocspRes.getStatus()); } BasicOCSPResp res = (BasicOCSPResp) ocspRes.getResponseObject(); SingleResp[] responses = res.getResponses(); SingleResp response = responses[0]; CertificateStatus status = (CertificateStatus) response.getCertStatus(); // Normal OCSP protocol allows a null status return status == null || status == CertificateStatus.GOOD; } catch (IOException e) { throw new NetworkAccessException("I/O error occured", e); } catch (OCSPException e) { throw new VerificationException("Error while following OCSP protocol", e); } finally { if (post != null) { post.releaseConnection(); } } }