List of usage examples for org.apache.commons.httpclient.methods EntityEnclosingMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:com.cordys.coe.ac.httpconnector.impl.StandardRequestHandler.java
/** * @see IRequestHandler#process(int, IServerConnection, HttpClient) */// www.j a v a 2 s . com @Override public HttpMethod process(int requestNode, IServerConnection connection, HttpClient httpClient) throws HandlerException { String uri = getRequestUri(requestNode, connection, httpClient); EntityEnclosingMethod httpMethod; if (LOG.isDebugEnabled()) { LOG.debug("HTTP method is: " + m_method.getHttpMethodType()); } switch (m_method.getHttpMethodType()) { case GET: HttpMethod httpMethodGet = new GetMethod(uri); // Get method does not have a body. setRequestHeaders(httpMethodGet); return httpMethodGet; case POST: httpMethod = new PostMethod(uri); break; case PUT: httpMethod = new PutMethod(uri); break; case DELETE: HttpMethod httpMethodDelete = new DeleteMethod(uri); // Delete method does not have a body. setRequestHeaders(httpMethodDelete); return httpMethodDelete; default: throw new HandlerException(HandlerExceptionMessages.UNKNOWN_HTTP_METHOD); } int reqNode = requestNode; try { reqNode = preProcessXml(reqNode, reqNode != requestNode); if (xsltNode != 0) { reqNode = executeXslt(reqNode, m_method, reqNode != requestNode); } if (m_requestRootXPath != null) { reqNode = handleRequestXPath(reqNode, m_method, reqNode != requestNode); } if ((m_removeNamespaceUriSet != null) || m_removeAllNamespaces) { XmlUtils.removeNamespacesRecursively(reqNode, m_removeNamespaceUriSet); } reqNode = postProcessXml(reqNode, reqNode != requestNode); if (LOG.isDebugEnabled()) { LOG.debug("Final Request XML: " + Node.writeToString(reqNode, true)); } // Get the data that should be posted. byte[] reqData = getPostData(reqNode, connection); String contentType = getContentType(); httpMethod.setRequestEntity(new ByteArrayRequestEntity(reqData, contentType)); if (LOG.isDebugEnabled()) { LOG.debug("Sending data: " + new String(reqData)); } httpMethod.setRequestHeader("Content-type", contentType); setRequestHeaders(httpMethod); } finally { if ((reqNode != 0) && (reqNode != requestNode)) { Node.delete(reqNode); reqNode = 0; } } return httpMethod; }
From source file:com.groupon.odo.HttpUtilities.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same standard POST data * as was sent in the given {@link HttpServletRequest} * * @param methodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a * standard POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the POST data to * be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} * @param history The {@link com.groupon.odo.proxylib.models.History} log for this request *//*from w ww. j a v a 2 s.com*/ @SuppressWarnings("unchecked") public static void handleStandardPost(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest, History history) throws Exception { String deserialisedMessages = ""; byte[] requestByteArray = null; // Create a new StringBuffer with the data to be passed StringBuilder requestBody = new StringBuilder(); InputStream body = httpServletRequest.getInputStream(); java.util.Scanner s = new java.util.Scanner(body).useDelimiter("\\A"); if (httpServletRequest.getContentType() != null && httpServletRequest.getContentType().contains(STRING_CONTENT_TYPE_FORM_URLENCODED)) { // Get the client POST data as a Map if content type is: application/x-www-form-urlencoded // We do this manually since some data is not properly parseable by the servlet request Map<String, String[]> mapPostParameters = HttpUtilities.mapUrlEncodedParameters(httpServletRequest); // Iterate the parameter names for (String stringParameterName : mapPostParameters.keySet()) { // Iterate the values for each parameter name String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName); for (String stringParameterValue : stringArrayParameterValues) { // Create a NameValuePair and store in list // add an & if there is already data if (requestBody.length() > 0) { requestBody.append("&"); } requestBody.append(stringParameterName); // not everything has a value so lets check if (stringParameterValue.length() > 0) { requestBody.append("="); requestBody.append(stringParameterValue); } } } } else if (httpServletRequest.getContentType() != null && httpServletRequest.getContentType().contains(STRING_CONTENT_TYPE_MESSAGEPACK)) { /** * Convert input stream to bytes for it to be read by the deserializer * Unpack and iterate the list to see the contents */ MessagePack msgpack = new MessagePack(); requestByteArray = IOUtils.toByteArray(body); ByteArrayInputStream byteArrayIS = new ByteArrayInputStream(requestByteArray); Unpacker unpacker = msgpack.createUnpacker(byteArrayIS); for (Value message : unpacker) { deserialisedMessages += message; deserialisedMessages += "\n"; } } else { // just set the request body to the POST body if (s.hasNext()) { requestBody.append(s.next()); } } // Set the proxy request data StringRequestEntity stringEntity = new StringRequestEntity(requestBody.toString(), null, null); // set post body in history object history.setRequestPostData(requestBody.toString()); // set post body in proxy request object methodProxyRequest.setRequestEntity(stringEntity); /** * Set the history to have decoded messagepack. Pass the byte data back to request */ if (httpServletRequest.getContentType() != null && httpServletRequest.getContentType().contains(STRING_CONTENT_TYPE_MESSAGEPACK)) { history.setRequestPostData(deserialisedMessages); ByteArrayRequestEntity byteRequestEntity = new ByteArrayRequestEntity(requestByteArray); methodProxyRequest.setRequestEntity(byteRequestEntity); } }
From source file:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Sets up the given {@link EntityEnclosingMethod} to send the same multipart * data as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are * configuring to send a multipart request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the mutlipart data to be sent via the {@link EntityEnclosingMethod} *///from w ww . j av a2 s . co m private void handleMultipartPost(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest) throws ServletException { // 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[] {}), entityEnclosingMethod.getParams()); entityEnclosingMethod.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 entityEnclosingMethod.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:com.xmlcalabash.library.ApacheHttpRequest.java
private void doPutOrPost(EntityEnclosingMethod method, XdmNode body) { // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); for (Header header : headers) { method.addRequestHeader(header); }/*from w w w .j a v a 2 s. c o m*/ contentType = body.getAttributeValue(_content_type); if (contentType == null) { throw new XProcException("Content-type on c:body is required."); } // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it String postContent = null; try { if (xmlContentType(contentType)) { Serializer serializer = makeSerializer(); Vector<XdmNode> content = new Vector<XdmNode>(); XdmSequenceIterator iter = body.axisIterator(Axis.CHILD); while (iter.hasNext()) { XdmNode node = (XdmNode) iter.next(); content.add(node); } // FIXME: set serializer properties appropriately! StringWriter writer = new StringWriter(); serializer.setOutputWriter(writer); S9apiUtils.serialize(runtime, content, serializer); writer.close(); postContent = writer.toString(); } else { StringWriter writer = new StringWriter(); XdmSequenceIterator iter = body.axisIterator(Axis.CHILD); while (iter.hasNext()) { XdmNode node = (XdmNode) iter.next(); writer.write(node.getStringValue()); } writer.close(); postContent = writer.toString(); } StringRequestEntity requestEntity = new StringRequestEntity(postContent, contentType, "UTF-8"); method.setRequestEntity(requestEntity); } catch (IOException ioe) { throw new XProcException(ioe); } catch (SaxonApiException sae) { throw new XProcException(sae); } }
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
public byte[] getData(Context context) throws IOException, EngineException { HttpMethod method = null;// ww w .ja va2 s .c o m try { // Fire event for plugins long t0 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context); // Retrieving httpState getHttpState(context); Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array..."); Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl); // Setting the referer referer = sUrl; URL url = null; url = new URL(sUrl); // Proxy configuration Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url); Engine.logBeans.debug("(HttpConnector) Https: " + https); String host = ""; int port = -1; if (sUrl.toLowerCase().startsWith("https:")) { if (!https) { Engine.logBeans.debug("(HttpConnector) Setting up SSL properties"); certificateManager.collectStoreInformation(context); } url = new URL(sUrl); host = url.getHost(); port = url.getPort(); if (port == -1) port = 443; Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); Engine.logBeans .debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged); if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != port)) { Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket"); Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, this.trustAllServerCertificates), port); hostConfiguration.setHost(host, port, myhttps); } sUrl = url.getFile(); Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl); } else { url = new URL(sUrl); host = url.getHost(); port = url.getPort(); Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); hostConfiguration.setHost(host, port); } AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction; // Retrieve HTTP method HttpMethodType httpVerb = httpTransaction.getHttpVerb(); String sHttpVerb = httpVerb.name(); final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb(); if (sCustomHttpVerb.length() > 0) { Engine.logBeans.debug( "(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'"); switch (httpVerb) { case GET: method = new GetMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case POST: method = new PostMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case PUT: method = new PutMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case DELETE: method = new DeleteMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case HEAD: method = new HeadMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case OPTIONS: method = new OptionsMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case TRACE: method = new TraceMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; } } else { Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb); switch (httpVerb) { case GET: method = new GetMethod(sUrl); break; case POST: method = new PostMethod(sUrl); break; case PUT: method = new PutMethod(sUrl); break; case DELETE: method = new DeleteMethod(sUrl); break; case HEAD: method = new HeadMethod(sUrl); break; case OPTIONS: method = new OptionsMethod(sUrl); break; case TRACE: method = new TraceMethod(sUrl); break; } } // Setting HTTP parameters boolean hasUserAgent = false; for (List<String> httpParameter : httpParameters) { String key = httpParameter.get(0); String value = httpParameter.get(1); if (key.equalsIgnoreCase("host") && !value.equals(host)) { value = host; } if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) { method.setRequestHeader(key, value); } if (HeaderName.UserAgent.is(key)) { hasUserAgent = true; } } // set user-agent header if not found if (!hasUserAgent) { HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context)); } // Setting POST or PUT parameters if any Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data"); if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method; AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject; if (doMultipartFormData) { RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction .getVariable(Parameter.HttpBody.getName()); if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) { String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName()); String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue, getProject().getName()); File file = new File(filepath); if (file.exists()) { HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType)); } else { throw new FileNotFoundException(file.getAbsolutePath()); } } else { List<Part> parts = new LinkedList<Part>(); for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if ("POST".equals(httpVariable.getHttpMethod())) { Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addFormDataPart(parts, httpVariable, httpVariableValue); } } } else { addFormDataPart(parts, httpVariable, httpObjectVariableValue); } } } } MultipartRequestEntity mre = new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams()); HeaderName.ContentType.setRequestHeader(method, mre.getContentType()); entityEnclosingMethod.setRequestEntity(mre); } } else if (MimeType.TextXml.is(contentType)) { final MimeMultipart[] mp = { null }; for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) { Engine.logBeans.trace( "(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM"); MimeMultipart mimeMultipart = mp[0]; try { if (mimeMultipart == null) { Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request"); mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\""); MimeBodyPart bp = new MimeBodyPart(); bp.setText(postQuery, "UTF-8"); bp.setHeader(HeaderName.ContentType.value(), contentType); mimeMultipart.addBodyPart(bp); } Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addMtomPart(mimeMultipart, httpVariable, httpVariableValue); } } } else { addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue); } mp[0] = mimeMultipart; } catch (Exception e) { Engine.logBeans.warn( "(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(), e); } } } } if (mp[0] == null) { entityEnclosingMethod.setRequestEntity( new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8")); } else { Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: " + mp[0].getContentType()); HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType()); entityEnclosingMethod.setRequestEntity(new RequestEntity() { @Override public void writeRequest(OutputStream outputStream) throws IOException { try { mp[0].writeTo(outputStream); } catch (MessagingException e) { new IOException(e); } } @Override public boolean isRepeatable() { return true; } @Override public String getContentType() { return mp[0].getContentType(); } @Override public long getContentLength() { return -1; } }); } } else { String charset = httpTransaction.getComputedUrlEncodingCharset(); HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod .setRequestEntity(new StringRequestEntity(postQuery, contentType, charset)); } } // Getting the result Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body"); byte[] result = executeMethod(method, context); Engine.logBeans.debug("(HttpConnector) Total read bytes: " + ((result != null) ? result.length : 0)); // Fire event for plugins long t1 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1); fireDataChanged(new ConnectorEvent(this, result)); return result; } finally { if (method != null) method.releaseConnection(); } }
From source file:com.xmlcalabash.library.HttpRequest.java
private void doPutOrPostSinglepart(EntityEnclosingMethod method, XdmNode body) { // ATTENTION: This doesn't handle multipart, that's done entirely separately // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Check for consistency of content-type contentType = body.getAttributeValue(_content_type); if (contentType == null) { throw new XProcException(step.getNode(), "Content-type on c:body is required."); }// w w w . j av a 2s. c o m if (headerContentType != null && !headerContentType.equals(contentType.toLowerCase())) { throw XProcException.stepError(20); } for (Header header : headers) { method.addRequestHeader(header); } // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it String postContent = null; String encoding = body.getAttributeValue(_encoding); try { if ("base64".equals(encoding)) { String charset = body.getAttributeValue(_charset); // FIXME: is utf-8 the right default? if (charset == null) { charset = "utf-8"; } String escapedContent = decodeBase64(body, charset); StringWriter writer = new StringWriter(); writer.write(escapedContent); writer.close(); postContent = writer.toString(); } else { if (jsonContentType(contentType)) { postContent = XMLtoJSON.convert(body); } else if (xmlContentType(contentType)) { Serializer serializer = makeSerializer(); if (!S9apiUtils.isDocumentContent(body.axisIterator(Axis.CHILD))) { throw XProcException.stepError(22); } Vector<XdmNode> content = new Vector<XdmNode>(); XdmSequenceIterator iter = body.axisIterator(Axis.CHILD); while (iter.hasNext()) { XdmNode node = (XdmNode) iter.next(); content.add(node); } // FIXME: set serializer properties appropriately! StringWriter writer = new StringWriter(); serializer.setOutputWriter(writer); S9apiUtils.serialize(runtime, content, serializer); writer.close(); postContent = writer.toString(); } else { StringWriter writer = new StringWriter(); XdmSequenceIterator iter = body.axisIterator(Axis.CHILD); while (iter.hasNext()) { XdmNode node = (XdmNode) iter.next(); if (node.getNodeKind() != XdmNodeKind.TEXT) { throw XProcException.stepError(28); } writer.write(node.getStringValue()); } writer.close(); postContent = writer.toString(); } } StringRequestEntity requestEntity = new StringRequestEntity(postContent, contentType, "UTF-8"); method.setRequestEntity(requestEntity); } catch (IOException ioe) { throw new XProcException(ioe); } catch (SaxonApiException sae) { throw new XProcException(sae); } }
From source file:it.geosolutions.httpproxy.HTTPProxy.java
/** * Sets up the given {@link PostMethod} to send the same multipart POST data as was sent in the given {@link HttpServletRequest} * /*from w w w.j a va 2 s. c o m*/ * @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} */ private void handleMultipart(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest) throws ServletException { // //////////////////////////////////////////// // Create a factory for disk-based file items // //////////////////////////////////////////// DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // ///////////////////////////// // Set factory constraints // ///////////////////////////// diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(Utils.DEFAULT_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( // The field name fileItemCurrent.getFieldName(), // The field value fileItemCurrent.getString()); // //////////////////////////// // 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( // ///////////////////// // The field name // ///////////////////// fileItemCurrent.getFieldName(), new ByteArrayPartSource( // The uploaded file name fileItemCurrent.getName(), // The uploaded file contents fileItemCurrent.get())); // ///////////////////////////// // Add the part to the list // ///////////////////////////// listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), methodProxyRequest.getParams()); methodProxyRequest.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 // //////////////////////////////////////////////////////////////////////// methodProxyRequest.setRequestHeader(Utils.CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:com.xmlcalabash.library.HttpRequest.java
private void doPutOrPostMultipart(EntityEnclosingMethod method, XdmNode multipart) { // The Apache HTTP libraries just don't handle this case...we treat it as a "single part" // and build the body ourselves, using the boundaries etc. // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Check for consistency of content-type contentType = multipart.getAttributeValue(_content_type); if (contentType == null) { contentType = "multipart/mixed"; }//from ww w . j av a 2s.co m if (headerContentType != null && !headerContentType.equals(contentType.toLowerCase())) { throw XProcException.stepError(20); } if (!contentType.startsWith("multipart/")) { throw new UnsupportedOperationException("Multipart content-type must be multipart/..."); } for (Header header : headers) { method.addRequestHeader(header); } String boundary = multipart.getAttributeValue(_boundary); if (boundary == null) { throw new XProcException(step.getNode(), "A boundary value must be specified on c:multipart"); } if (boundary.startsWith("--")) { throw XProcException.stepError(2); } String q = "\""; if (boundary.contains(q)) { q = "'"; } if (boundary.contains(q)) { q = ""; } String multipartContentType = contentType + "; boundary=" + q + boundary + q; // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it MessageBytes byteContent = new MessageBytes(); byteContent.append("This is a multipart message.\r\n"); //String postContent = "This is a multipart message.\r\n"; for (XdmNode body : new RelevantNodes(runtime, multipart, Axis.CHILD)) { if (!XProcConstants.c_body.equals(body.getNodeName())) { throw new XProcException(step.getNode(), "A c:multipart may only contain c:body elements."); } String bodyContentType = body.getAttributeValue(_content_type); if (bodyContentType == null) { throw new XProcException(step.getNode(), "Content-type on c:body is required."); } String bodyId = body.getAttributeValue(_id); String bodyDescription = body.getAttributeValue(_description); String bodyDisposition = body.getAttributeValue(_disposition); String bodyCharset = HttpUtils.getCharset(bodyContentType); if (bodyContentType.contains(";")) { int pos = bodyContentType.indexOf(";"); bodyContentType = bodyContentType.substring(0, pos); } String bodyEncoding = body.getAttributeValue(_encoding); if (bodyEncoding != null && !"base64".equals(bodyEncoding)) { throw new UnsupportedOperationException("The '" + bodyEncoding + "' encoding is not supported"); } if (bodyCharset != null) { bodyContentType += "; charset=" + bodyCharset; } else { // Is utf-8 the right default? What about the image/ case? bodyContentType += "; charset=utf-8"; } //postContent += "--" + boundary + "\r\n"; //postContent += "Content-Type: " + bodyContentType + "\r\n"; byteContent.append("--" + boundary + "\r\n"); byteContent.append("Content-Type: " + bodyContentType + "\r\n"); if (bodyDescription != null) { //postContent += "Content-Description: " + bodyDescription + "\r\n"; byteContent.append("Content-Description: " + bodyDescription + "\r\n"); } if (bodyId != null) { //postContent += "Content-ID: " + bodyId + "\r\n"; byteContent.append("Content-ID: " + bodyId + "\r\n"); } if (bodyDisposition != null) { //postContent += "Content-Disposition: " + bodyDisposition + "\r\n"; byteContent.append("Content-Disposition: " + bodyDisposition + "\r\n"); } if (bodyEncoding != null) { //postContent += "Content-Transfer-Encoding: " + bodyEncoding + "\r\n"; if (encodeBinary) { byteContent.append("Content-Transfer-Encoding: " + bodyEncoding + "\r\n"); } } //postContent += "\r\n"; byteContent.append("\r\n"); try { if (xmlContentType(bodyContentType)) { Serializer serializer = makeSerializer(); Vector<XdmNode> content = new Vector<XdmNode>(); XdmSequenceIterator iter = body.axisIterator(Axis.CHILD); while (iter.hasNext()) { XdmNode node = (XdmNode) iter.next(); content.add(node); } // FIXME: set serializer properties appropriately! StringWriter writer = new StringWriter(); serializer.setOutputWriter(writer); S9apiUtils.serialize(runtime, content, serializer); writer.close(); //postContent += writer.toString(); byteContent.append(writer.toString()); } else if (jsonContentType(contentType)) { byteContent.append(XMLtoJSON.convert(body)); } else if (!encodeBinary && "base64".equals(bodyEncoding)) { byte[] decoded = Base64.decode(body.getStringValue()); byteContent.append(decoded, decoded.length); } else { StringWriter writer = new StringWriter(); XdmSequenceIterator iter = body.axisIterator(Axis.CHILD); while (iter.hasNext()) { XdmNode node = (XdmNode) iter.next(); if (node.getNodeKind() != XdmNodeKind.TEXT) { throw XProcException.stepError(28); } writer.write(node.getStringValue()); } writer.close(); //postContent += writer.toString(); byteContent.append(writer.toString()); } //postContent += "\r\n"; byteContent.append("\r\n"); } catch (IOException ioe) { throw new XProcException(ioe); } catch (SaxonApiException sae) { throw new XProcException(sae); } } //postContent += "--" + boundary + "--\r\n"; byteContent.append("--" + boundary + "--\r\n"); ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(byteContent.content(), multipartContentType); //StringRequestEntity requestEntity = new StringRequestEntity(postContent, multipartContentType, null); method.setRequestEntity(requestEntity); }
From source file:org.alfresco.rest.api.tests.client.AuthenticatedHttp.java
/** * Adds the JSON as request-body the the method and sets the correct * content-type.//from w w w . j a v a 2 s. c om * @param method EntityEnclosingMethod * @param object JSONObject */ private void populateRequestBody(EntityEnclosingMethod method, JSONObject object) { try { method.setRequestEntity(new StringRequestEntity(object.toJSONString(), MIME_TYPE_JSON, "UTF-8")); } catch (UnsupportedEncodingException error) { // This will never happen! throw new RuntimeException("All hell broke loose, a JVM that doesn't have UTF-8 encoding..."); } }
From source file:org.apache.abdera.protocol.client.util.MethodHelper.java
private static EntityEnclosingMethod getMethod(EntityEnclosingMethod method, RequestEntity entity) { if (entity != null) method.setRequestEntity(entity); return method; }