List of usage examples for org.apache.commons.httpclient.methods ByteArrayRequestEntity ByteArrayRequestEntity
public ByteArrayRequestEntity(byte[] paramArrayOfByte, String paramString)
From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java
protected void setupEntityMethod(Object src, String encoding, MuleMessage msg, EntityEnclosingMethod postMethod) throws UnsupportedEncodingException, TransformerException { // Dont set a POST payload if the body is a Null Payload. // This way client calls can control if a POST body is posted explicitly if (!(msg.getPayload() instanceof NullPayload)) { String outboundMimeType = (String) msg.getProperty(HttpConstants.HEADER_CONTENT_TYPE, PropertyScope.OUTBOUND); if (outboundMimeType == null) { outboundMimeType = (getEndpoint() != null ? getEndpoint().getMimeType() : null); }//from www.jav a2 s .c o m if (outboundMimeType == null) { outboundMimeType = HttpConstants.DEFAULT_CONTENT_TYPE; logger.info("Content-Type not set on outgoing request, defaulting to: " + outboundMimeType); } if (encoding != null && !"UTF-8".equals(encoding.toUpperCase()) && outboundMimeType.indexOf("charset") == -1) { outboundMimeType += "; charset=" + encoding; } // Ensure that we have a cached representation of the message if we're // using HTTP 1.0 final String httpVersion = msg.getOutboundProperty(HttpConnector.HTTP_VERSION_PROPERTY, HttpConstants.HTTP11); if (HttpConstants.HTTP10.equals(httpVersion)) { try { src = msg.getPayloadAsBytes(); } catch (final Exception e) { throw new TransformerException(this, e); } } if (msg.getOutboundAttachmentNames() != null && msg.getOutboundAttachmentNames().size() > 0) { try { postMethod.setRequestEntity(createMultiPart(msg, postMethod)); return; } catch (final Exception e) { throw new TransformerException(this, e); } } if (src instanceof String) { postMethod.setRequestEntity(new StringRequestEntity(src.toString(), outboundMimeType, encoding)); return; } if (src instanceof InputStream) { postMethod.setRequestEntity(new InputStreamRequestEntity((InputStream) src, outboundMimeType)); } else if (src instanceof byte[]) { postMethod.setRequestEntity(new ByteArrayRequestEntity((byte[]) src, outboundMimeType)); } else if (src instanceof OutputHandler) { final MuleEvent event = RequestContext.getEvent(); postMethod.setRequestEntity(new StreamPayloadRequestEntity((OutputHandler) src, event)); } else { final byte[] buffer = SerializationUtils.serialize((Serializable) src); postMethod.setRequestEntity(new ByteArrayRequestEntity(buffer, outboundMimeType)); } } else if (msg.getOutboundAttachmentNames() != null && msg.getOutboundAttachmentNames().size() > 0) { try { postMethod.setRequestEntity(createMultiPart(msg, postMethod)); } catch (Exception e) { throw new TransformerException(this, e); } } }
From source file:org.mule.transport.legstar.test.jvmquery.JvmqueryHttpClientTest.java
/** * Use HTTP client to post binary data and receive a binary reply. * @param hostByteArray the request data * @return the response data as an hexadecimal string * @throws IOException general IO failure *//*from w w w . ja va2 s . c o m*/ private String postRequest(final byte[] hostByteArray) throws IOException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(JVMQUERY_PROXY_URL); ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(hostByteArray, "application/octet-stream"); postMethod.setRequestEntity(requestEntity); if (200 != httpClient.executeMethod(postMethod)) { throw new IOException(postMethod.getStatusText()); } return HostData.toHexString(postMethod.getResponseBody()); }
From source file:org.mule.transport.legstar.test.jvmquery.JvmqueryHttpTest.java
/** * Invoke the proxy deployed at the specified URL. * @param mainframeRequestData a hex string of the raw mainframe data * @param expectedResponseSize the size in bytes of the expected response * @return a hex string of the mainframe response data * @throws Exception if invoke fails/* w w w . j a va2 s .c om*/ */ public String invoke(final String mainframeRequestData, final int expectedResponseSize) throws Exception { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(JVMQUERY_PROXY_URL); ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity( HostData.toByteArray(mainframeRequestData), "application/octet-stream"); postMethod.setRequestEntity(requestEntity); if (200 != httpClient.executeMethod(postMethod)) { throw new IOException(postMethod.getStatusText()); } if (expectedResponseSize != postMethod.getResponseContentLength()) { throw new IOException("Content length returned does not match"); } return HostData.toHexString(postMethod.getResponseBody()); }
From source file:org.mule.transport.legstar.test.lsfileae.LsfileaeHttpClientTest.java
/** * Use HTTP client to post binary data and receive a binary reply. * @param serializedJavaObject the request data * @return the response data as a stream * @throws IOException general IO failure *//* w w w .ja va 2 s. c om*/ private InputStream postRequest(final byte[] serializedJavaObject) throws IOException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(LSFILEAE_ADAPTER_URL); ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(serializedJavaObject, "application/octet-stream"); postMethod.setRequestEntity(requestEntity); if (200 != httpClient.executeMethod(postMethod)) { throw new IOException(postMethod.getStatusText()); } return postMethod.getResponseBodyAsStream(); }
From source file:org.opensaml.ws.soap.client.http.HttpSOAPClient.java
/** * Creates the request entity that makes up the POST message body. * /*w w w. ja v a 2s. co m*/ * @param message message to be sent * @param charset character set used for the message * * @return request entity that makes up the POST message body * * @throws SOAPClientException thrown if the message could not be marshalled */ protected RequestEntity createRequestEntity(Envelope message, Charset charset) throws SOAPClientException { try { Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(message); ByteArrayOutputStream arrayOut = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(arrayOut, charset); if (log.isDebugEnabled()) { log.debug("Outbound SOAP message is:\n" + XMLHelper.prettyPrintXML(marshaller.marshall(message))); } XMLHelper.writeNode(marshaller.marshall(message), writer); return new ByteArrayRequestEntity(arrayOut.toByteArray(), "text/xml"); } catch (MarshallingException e) { throw new SOAPClientException("Unable to marshall SOAP envelope", e); } }
From source file:org.parosproxy.paros.network.GenericMethod.java
/** * Generates a request entity from the post parameters, if present. Calls * {@link EntityEnclosingMethod#generateRequestBody()} if parameters have not been set. * // w w w . j av a 2 s .co m * @since 3.0 */ @Override protected RequestEntity generateRequestEntity() { if (!this.params.isEmpty()) { // Use a ByteArrayRequestEntity instead of a StringRequestEntity. // This is to avoid potential encoding issues. Form url encoded strings // are ASCII by definition but the content type may not be. Treating the content // as bytes allows us to keep the current charset without worrying about how // this charset will effect the encoding of the form url encoded string. String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet()); ByteArrayRequestEntity entity = new ByteArrayRequestEntity(EncodingUtil.getAsciiBytes(content), FORM_URL_ENCODED_CONTENT_TYPE); return entity; } return super.generateRequestEntity(); }
From source file:org.pentaho.di.trans.steps.webservices.WebService.java
private synchronized void requestSOAP(Object[] rowData, RowMetaInterface rowMeta) throws KettleException { initWsdlEnv();// w w w.j a va2 s . c om PostMethod vHttpMethod = null; try { String xml = getRequestXML(cachedOperation, cachedWsdl.getWsdlTypes().isElementFormQualified(cachedWsdl.getTargetNamespace())); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "WebServices.Log.SOAPEnvelope")); logDetailed(xml); } try { vHttpMethod = getHttpMethod(cachedURLService); } catch (URIException e) { throw new KettleStepException( BaseMessages.getString(PKG, "WebServices.ERROR0002.InvalidURI", cachedURLService), e); } catch (UnsupportedEncodingException e) { throw new KettleStepException( BaseMessages.getString(PKG, "WebServices.ERROR0003.UnsupportedEncoding", cachedURLService), e); } RequestEntity requestEntity = new ByteArrayRequestEntity(xml.toString().getBytes("UTF-8"), "UTF-8"); vHttpMethod.setRequestEntity(requestEntity); // long currentRequestTime = Const.nanoTime(); int responseCode = cachedHttpClient.executeMethod(cachedHostConfiguration, vHttpMethod); if (responseCode == 200) { processRows(vHttpMethod.getResponseBodyAsStream(), rowData, rowMeta, cachedWsdl.getWsdlTypes().isElementFormQualified(cachedWsdl.getTargetNamespace()), vHttpMethod.getResponseCharSet()); } else if (responseCode == 401) { throw new KettleStepException( BaseMessages.getString(PKG, "WebServices.ERROR0011.Authentication", cachedURLService)); } else if (responseCode == 404) { throw new KettleStepException( BaseMessages.getString(PKG, "WebServices.ERROR0012.NotFound", cachedURLService)); } else { throw new KettleStepException(BaseMessages.getString(PKG, "WebServices.ERROR0001.ServerError", Integer.toString(responseCode), Const.NVL(new String(vHttpMethod.getResponseBody()), ""), cachedURLService)); } // requestTime += Const.nanoTime() - currentRequestTime; } catch (HttpException e) { throw new KettleStepException( BaseMessages.getString(PKG, "WebServices.ERROR0004.HttpException", cachedURLService), e); } catch (UnknownHostException e) { throw new KettleStepException( BaseMessages.getString(PKG, "WebServices.ERROR0013.UnknownHost", cachedURLService), e); } catch (IOException e) { throw new KettleStepException( BaseMessages.getString(PKG, "WebServices.ERROR0005.IOException", cachedURLService), e); } finally { data.argumentRows.clear(); // ready for the next batch. if (vHttpMethod != null) { vHttpMethod.releaseConnection(); } } }
From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java
protected static void handleRequestData(EntityEnclosingMethod method, Object data) { if (method == null) { throw new IllegalArgumentException("Invalid method, cannot be null"); }//from w w w.j a va 2 s . c o m if (data != null) { RequestEntity re = null; if (data.getClass().isAssignableFrom(InputStream.class)) { re = new InputStreamRequestEntity((InputStream) data, CONTENT_TYPE_UTF8); } else if (data.getClass().isAssignableFrom(byte[].class)) { re = new ByteArrayRequestEntity((byte[]) data, CONTENT_TYPE_UTF8); } else if (data.getClass().isAssignableFrom(File.class)) { re = new FileRequestEntity((File) data, CONTENT_TYPE_UTF8); } else { // handle as a string try { re = new StringRequestEntity(data.toString(), "text/xml", ENCODING_UTF8); } catch (UnsupportedEncodingException e) { throw new HttpIOException("Encoding data using UTF8 failed :: " + e.getMessage(), e); } } method.setRequestEntity(re); } }
From source file:org.sakaiproject.kernel.proxy.ProxyClientServiceImpl.java
/** * Executes a HTTP call using a path in the JCR to point to a template and a map of * properties to populate that template with. An example might be a SOAP call. * /*from w ww . j a v a 2 s . co m*/ * <pre> * {http://www.w3.org/2001/12/soap-envelope}Envelope:{ * {http://www.w3.org/2001/12/soap-envelope}Body:{ * {http://www.example.org/stock}GetStockPriceResponse:{ * >body:[ ] * {http://www.example.org/stock}Price:{ * >body:[34.5] * } * } * >body:[ ] * } * >body:[ ] * {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding] * } * * </pre> * * @param resource * the resource containing the proxy end point specification. * @param headers * a map of headers to set int the request. * @param input * a map of parameters for all templates (both url and body) * @param requestInputStream * containing the request body (can be null if the call requires no body or the * template will be used to generate the body) * @param requestContentLength * if the requestImputStream is specified, the length specifies the lenght of * the body. * @param requerstContentType * the content type of the request, if null the node property * sakai:proxy-request-content-type will be used. * @throws ProxyClientException */ public ProxyResponse executeCall(Node node, Map<String, String> headers, Map<String, String> input, InputStream requestInputStream, long requestContentLength, String requestContentType) throws ProxyClientException { try { bindNode(node); if (node != null && node.hasProperty(SAKAI_REQUEST_PROXY_ENDPOINT)) { VelocityContext context = new VelocityContext(input); // setup the post request String endpointURL = JcrUtils.getMultiValueString(node.getProperty(SAKAI_REQUEST_PROXY_ENDPOINT)); Reader urlTemplateReader = new StringReader(endpointURL); StringWriter urlWriter = new StringWriter(); velocityEngine.evaluate(context, urlWriter, "urlprocessing", urlTemplateReader); endpointURL = urlWriter.toString(); ProxyMethod proxyMethod = ProxyMethod.GET; if (node.hasProperty(SAKAI_REQUEST_PROXY_METHOD)) { try { proxyMethod = ProxyMethod.valueOf(node.getProperty(SAKAI_REQUEST_PROXY_METHOD).getString()); } catch (Exception e) { } } HttpMethod method = null; switch (proxyMethod) { case GET: method = new GetMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case HEAD: method = new HeadMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case OPTIONS: method = new OptionsMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case POST: method = new PostMethod(endpointURL); break; case PUT: method = new PutMethod(endpointURL); break; default: method = new GetMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); } // follow redirects, but dont auto process 401's and the like. // credentials should be provided method.setDoAuthentication(false); for (Entry<String, String> header : headers.entrySet()) { method.addRequestHeader(header.getKey(), header.getValue()); } Value[] additionalHeaders = JcrUtils.getValues(node, SAKAI_PROXY_HEADER); for (Value v : additionalHeaders) { String header = v.getString(); String[] keyVal = StringUtils.split(header, ':', 2); method.addRequestHeader(keyVal[0].trim(), keyVal[1].trim()); } if (method instanceof EntityEnclosingMethod) { String contentType = requestContentType; if (contentType == null && node.hasProperty(SAKAI_REQUEST_CONTENT_TYPE)) { contentType = node.getProperty(SAKAI_REQUEST_CONTENT_TYPE).getString(); } if (contentType == null) { contentType = APPLICATION_OCTET_STREAM; } EntityEnclosingMethod eemethod = (EntityEnclosingMethod) method; if (requestInputStream != null) { eemethod.setRequestEntity(new InputStreamRequestEntity(requestInputStream, requestContentLength, contentType)); } else { // build the request Template template = velocityEngine.getTemplate(node.getPath()); StringWriter body = new StringWriter(); template.merge(context, body); byte[] soapBodyContent = body.toString().getBytes("UTF-8"); eemethod.setRequestEntity(new ByteArrayRequestEntity(soapBodyContent, contentType)); } } int result = httpClient.executeMethod(method); if (result == 302 && method instanceof EntityEnclosingMethod) { // handle redirects on post and put String url = method.getResponseHeader("Location").getValue(); method = new GetMethod(url); method.setFollowRedirects(true); method.setDoAuthentication(false); result = httpClient.executeMethod(method); } return new ProxyResponseImpl(result, method); } } catch (Exception e) { throw new ProxyClientException("The Proxy request specified by " + node + " failed, cause follows:", e); } finally { unbindNode(); } throw new ProxyClientException( "The Proxy request specified by " + node + " does not contain a valid endpoint specification "); }
From source file:org.sakaiproject.nakamura.proxy.ProxyClientServiceImpl.java
/** * Executes a HTTP call using a path in the JCR to point to a template and a map of * properties to populate that template with. An example might be a SOAP call. * * <pre>//from w w w. j a v a 2 s . c o m * {http://www.w3.org/2001/12/soap-envelope}Envelope:{ * {http://www.w3.org/2001/12/soap-envelope}Body:{ * {http://www.example.org/stock}GetStockPriceResponse:{ * >body:[ ] * {http://www.example.org/stock}Price:{ * >body:[34.5] * } * } * >body:[ ] * } * >body:[ ] * {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding] * } * * </pre> * * @param resource * the resource containing the proxy end point specification. * @param headers * a map of headers to set int the request. * @param input * a map of parameters for all templates (both url and body) * @param requestInputStream * containing the request body (can be null if the call requires no body or the * template will be used to generate the body) * @param requestContentLength * if the requestImputStream is specified, the length specifies the lenght of * the body. * @param requerstContentType * the content type of the request, if null the node property * sakai:proxy-request-content-type will be used. * @throws ProxyClientException */ public ProxyResponse executeCall(Node node, Map<String, String> headers, Map<String, Object> input, InputStream requestInputStream, long requestContentLength, String requestContentType) throws ProxyClientException { try { bindNode(node); if (node != null && node.hasProperty(SAKAI_REQUEST_PROXY_ENDPOINT)) { // setup the post request String endpointURL = JcrUtils.getMultiValueString(node.getProperty(SAKAI_REQUEST_PROXY_ENDPOINT)); if (isUnsafeProxyDefinition(node)) { try { URL u = new URL(endpointURL); String host = u.getHost(); if (host.indexOf('$') >= 0) { throw new ProxyClientException( "Invalid Endpoint template, relies on request to resolve valid URL " + u); } } catch (MalformedURLException e) { throw new ProxyClientException( "Invalid Endpoint template, relies on request to resolve valid URL", e); } } // Find all velocity replacement variable(s) in the endpointURL, // copy any equivalent keys from the input Map, to a new Map that // can be process by Velocity. In the new Map, the Map value field // has been changed from RequestParameter[] to String. Map<String, String> inputContext = new HashMap<String, String>(); int startPosition = endpointURL.indexOf("${"); while (startPosition > -1) { int endPosition = endpointURL.indexOf("}", startPosition); if (endPosition > -1) { String key = endpointURL.substring(startPosition + 2, endPosition); Object value = input.get(key); if (value instanceof RequestParameter[]) { // now change input value object from RequestParameter[] to String // and add to inputContext Map. RequestParameter[] requestParameters = (RequestParameter[]) value; inputContext.put(key, requestParameters[0].getString()); } else { // KERN-1346 regression; see KERN-1409 inputContext.put(key, String.valueOf(value)); } // look for the next velocity replacement variable startPosition = endpointURL.indexOf("${", endPosition); } else { break; } } VelocityContext context = new VelocityContext(inputContext); // add in the config properties from the bundle overwriting everythign else. context.put("config", configProperties); endpointURL = processUrlTemplate(endpointURL, context); ProxyMethod proxyMethod = ProxyMethod.GET; if (node.hasProperty(SAKAI_REQUEST_PROXY_METHOD)) { try { proxyMethod = ProxyMethod.valueOf(node.getProperty(SAKAI_REQUEST_PROXY_METHOD).getString()); } catch (Exception e) { logger.debug("The Proxy request specified by " + node + " failed, cause follows:", e); } } HttpMethod method = null; switch (proxyMethod) { case GET: if (node.hasProperty(SAKAI_LIMIT_GET_SIZE)) { long maxSize = node.getProperty(SAKAI_LIMIT_GET_SIZE).getLong(); method = new HeadMethod(endpointURL); HttpMethodParams params = new HttpMethodParams(method.getParams()); // make certain we reject the body of a head params.setBooleanParameter("http.protocol.reject-head-body", true); method.setParams(params); method.setFollowRedirects(true); populateMethod(method, node, headers); int result = httpClient.executeMethod(method); if (externalAuthenticatingProxy && result == 407) { method.releaseConnection(); method.setDoAuthentication(true); result = httpClient.executeMethod(method); } if (result == 200) { // Check if the content-length is smaller than the maximum (if any). Header contentLengthHeader = method.getResponseHeader("Content-Length"); if (contentLengthHeader != null) { long length = Long.parseLong(contentLengthHeader.getValue()); if (length > maxSize) { return new ProxyResponseImpl(HttpServletResponse.SC_PRECONDITION_FAILED, "Response too large", method); } } } else { return new ProxyResponseImpl(result, method); } } method = new GetMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case HEAD: method = new HeadMethod(endpointURL); HttpMethodParams params = new HttpMethodParams(method.getParams()); // make certain we reject the body of a head params.setBooleanParameter("http.protocol.reject-head-body", true); method.setParams(params); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case OPTIONS: method = new OptionsMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case POST: method = new PostMethod(endpointURL); break; case PUT: method = new PutMethod(endpointURL); break; default: method = new GetMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); } populateMethod(method, node, headers); if (requestInputStream == null && !node.hasProperty(SAKAI_PROXY_REQUEST_TEMPLATE)) { if (method instanceof PostMethod) { PostMethod postMethod = (PostMethod) method; ArrayList<Part> parts = new ArrayList<Part>(); for (Entry<String, Object> param : input.entrySet()) { String key = param.getKey(); Object value = param.getValue(); if (value instanceof RequestParameter[]) { for (RequestParameter val : (RequestParameter[]) param.getValue()) { Part part = null; if (val.isFormField()) { part = new StringPart(param.getKey(), val.getString()); } else { ByteArrayPartSource source = new ByteArrayPartSource(key, val.get()); part = new FilePart(key, source); } parts.add(part); } } else { parts.add(new StringPart(key, value.toString())); } Part[] partsArray = parts.toArray(new Part[parts.size()]); postMethod.setRequestEntity(new MultipartRequestEntity(partsArray, method.getParams())); } } } else { if (method instanceof EntityEnclosingMethod) { String contentType = requestContentType; if (contentType == null && node.hasProperty(SAKAI_REQUEST_CONTENT_TYPE)) { contentType = node.getProperty(SAKAI_REQUEST_CONTENT_TYPE).getString(); } if (contentType == null) { contentType = APPLICATION_OCTET_STREAM; } EntityEnclosingMethod eemethod = (EntityEnclosingMethod) method; if (requestInputStream != null) { eemethod.setRequestEntity(new InputStreamRequestEntity(requestInputStream, requestContentLength, contentType)); } else { // build the request Template template = velocityEngine.getTemplate(node.getPath()); StringWriter body = new StringWriter(); template.merge(context, body); byte[] soapBodyContent = body.toString().getBytes("UTF-8"); eemethod.setRequestEntity(new ByteArrayRequestEntity(soapBodyContent, contentType)); } } } int result = httpClient.executeMethod(method); if (externalAuthenticatingProxy && result == 407) { method.releaseConnection(); method.setDoAuthentication(true); result = httpClient.executeMethod(method); } if (result == 302 && method instanceof EntityEnclosingMethod) { // handle redirects on post and put String url = method.getResponseHeader("Location").getValue(); method = new GetMethod(url); method.setFollowRedirects(true); method.setDoAuthentication(false); result = httpClient.executeMethod(method); if (externalAuthenticatingProxy && result == 407) { method.releaseConnection(); method.setDoAuthentication(true); result = httpClient.executeMethod(method); } } return new ProxyResponseImpl(result, method); } } catch (ProxyClientException e) { throw e; } catch (Exception e) { throw new ProxyClientException("The Proxy request specified by " + node + " failed, cause follows:", e); } finally { unbindNode(); } throw new ProxyClientException( "The Proxy request specified by " + node + " does not contain a valid endpoint specification "); }