List of usage examples for org.apache.commons.httpclient.methods EntityEnclosingMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:org.parosproxy.paros.network.HttpMethodHelper.java
public HttpMethod createRequestMethodNew(HttpRequestHeader header, HttpBody body) throws URIException { HttpMethod httpMethod = null;/* w w w. j a v a 2 s. c o m*/ String method = header.getMethod(); URI uri = header.getURI(); String version = header.getVersion(); httpMethod = new GenericMethod(method); httpMethod.setURI(uri); HttpMethodParams httpParams = httpMethod.getParams(); // default to use HTTP 1.0 httpParams.setVersion(HttpVersion.HTTP_1_0); if (version.equalsIgnoreCase(HttpHeader.HTTP11)) { httpParams.setVersion(HttpVersion.HTTP_1_1); } // set various headers int pos = 0; // ZAP: FindBugs fix - always initialise pattern Pattern pattern = patternCRLF; String delimiter = CRLF; String msg = header.getHeadersAsString(); if ((pos = msg.indexOf(CRLF)) < 0) { if ((pos = msg.indexOf(LF)) < 0) { delimiter = LF; pattern = patternLF; } } else { delimiter = CRLF; pattern = patternCRLF; } String[] split = pattern.split(msg); String token = null; String name = null; String value = null; //String host = null; for (int i = 0; i < split.length; i++) { token = split[i]; if (token.equals("")) { continue; } if ((pos = token.indexOf(":")) < 0) { return null; } name = token.substring(0, pos).trim(); value = token.substring(pos + 1).trim(); httpMethod.addRequestHeader(name, value); } // set body if post method or put method if (body != null && body.length() > 0) { EntityEnclosingMethod generic = (EntityEnclosingMethod) httpMethod; // generic.setRequestEntity(new StringRequestEntity(body.toString())); generic.setRequestEntity(new ByteArrayRequestEntity(body.getBytes())); } httpMethod.setFollowRedirects(false); return httpMethod; }
From source file:org.parosproxy.paros.network.HttpMethodHelper.java
public HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body) throws URIException { HttpMethod httpMethod = null;//from w ww. j a va 2 s . com String method = header.getMethod(); URI uri = header.getURI(); String version = header.getVersion(); if (method == null || method.trim().length() < 3) { throw new URIException("Invalid HTTP method: " + method); } if (method.equalsIgnoreCase(GET)) { //httpMethod = new GetMethod(); // ZAP: avoid discarding HTTP status code 101 that is used for WebSocket upgrade httpMethod = new ZapGetMethod(); } else if (method.equalsIgnoreCase(POST)) { httpMethod = new ZapPostMethod(); } else if (method.equalsIgnoreCase(DELETE)) { httpMethod = new ZapDeleteMethod(); } else if (method.equalsIgnoreCase(PUT)) { httpMethod = new ZapPutMethod(); } else if (method.equalsIgnoreCase(HEAD)) { httpMethod = new ZapHeadMethod(); } else if (method.equalsIgnoreCase(OPTIONS)) { httpMethod = new ZapOptionsMethod(); } else if (method.equalsIgnoreCase(TRACE)) { httpMethod = new ZapTraceMethod(uri.toString()); } else { httpMethod = new GenericMethod(method); } try { httpMethod.setURI(uri); } catch (Exception e1) { logger.error(e1.getMessage(), e1); } HttpMethodParams httpParams = httpMethod.getParams(); // default to use HTTP 1.0 httpParams.setVersion(HttpVersion.HTTP_1_0); if (version.equalsIgnoreCase(HttpHeader.HTTP11)) { httpParams.setVersion(HttpVersion.HTTP_1_1); } // set various headers int pos = 0; // ZAP: changed to always use CRLF, like the HttpHeader Pattern pattern = patternCRLF; String delimiter = header.getLineDelimiter(); // ZAP: Shouldn't happen as the HttpHeader always uses CRLF if (delimiter.equals(LF)) { delimiter = LF; pattern = patternLF; } String msg = header.getHeadersAsString(); String[] split = pattern.split(msg); String token = null; String name = null; String value = null; for (int i = 0; i < split.length; i++) { token = split[i]; if (token.equals("")) { continue; } if ((pos = token.indexOf(":")) < 0) { return null; } name = token.substring(0, pos).trim(); value = token.substring(pos + 1).trim(); httpMethod.addRequestHeader(name, value); } // set body if post method or put method if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) { EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod; // post.setRequestEntity(new StringRequestEntity(body.toString())); post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes())); } httpMethod.setFollowRedirects(false); return httpMethod; }
From source file:org.pentaho.di.baserver.utils.web.HttpConnectionHelper.java
private void setRequestEntity(EntityEnclosingMethod method, Map<String, String> queryParameters) { try {/*w ww . j a v a 2 s .c o m*/ // TODO: this supports only FormParameters, need to support MultiPart messages with files, // simple string values with JSON and XML, plain text, both body and query parameters for PUT String queryString = constructQueryString(queryParameters); if (!queryString.isEmpty()) { queryString = queryString.substring(1); } method.setRequestEntity( new StringRequestEntity(queryString, "application/x-www-form-urlencoded", UTF_8)); } catch (UnsupportedEncodingException e) { logger.error("Failed", e); } }
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"); }// www. ja v a2 s .c om 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. * // w w w . j ava2 s .c o 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 ava 2 s.co 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 "); }
From source file:org.sonar.wsclient.connectors.HttpClient3Connector.java
private void setRequestEntity(EntityEnclosingMethod request, AbstractQuery<?> query) { if (query.getBody() != null) { try {//from w w w . j ava2 s .c om request.setRequestEntity( new StringRequestEntity(query.getBody(), "text/plain; charset=UTF-8", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new ConnectionException("Unsupported encoding", e); } } }
From source file:org.tuckey.web.filters.urlrewrite.RequestProxy.java
/** * This method performs the proxying of the request to the target address. * * @param target The target address. Has to be a fully qualified address. The request is send as-is to this address. * @param hsRequest The request data which should be send to the * @param hsResponse The response data which will contain the data returned by the proxied request to target. * @throws java.io.IOException Passed on from the connection logic. *///ww w .jav a 2 s . c o m public static void execute(final String target, final HttpServletRequest hsRequest, final HttpServletResponse hsResponse) throws IOException { if (log.isInfoEnabled()) { log.info("execute, target is " + target); log.info("response commit state: " + hsResponse.isCommitted()); } if (StringUtils.isBlank(target)) { log.error("The target address is not given. Please provide a target address."); return; } log.info("checking url"); final URL url; try { url = new URL(target); } catch (MalformedURLException e) { log.error("The provided target url is not valid.", e); return; } log.info("seting up the host configuration"); final HostConfiguration config = new HostConfiguration(); ProxyHost proxyHost = getUseProxyServer((String) hsRequest.getAttribute("use-proxy")); if (proxyHost != null) config.setProxyHost(proxyHost); final int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort(); config.setHost(url.getHost(), port, url.getProtocol()); if (log.isInfoEnabled()) log.info("config is " + config.toString()); final HttpMethod targetRequest = setupProxyRequest(hsRequest, url); if (targetRequest == null) { log.error("Unsupported request method found: " + hsRequest.getMethod()); return; } //perform the reqeust to the target server final HttpClient client = new HttpClient(new SimpleHttpConnectionManager()); if (log.isInfoEnabled()) { log.info("client state" + client.getState()); log.info("client params" + client.getParams().toString()); log.info("executeMethod / fetching data ..."); } final int result; if (targetRequest instanceof EntityEnclosingMethod) { final RequestProxyCustomRequestEntity requestEntity = new RequestProxyCustomRequestEntity( hsRequest.getInputStream(), hsRequest.getContentLength(), hsRequest.getContentType()); final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) targetRequest; entityEnclosingMethod.setRequestEntity(requestEntity); result = client.executeMethod(config, entityEnclosingMethod); } else { result = client.executeMethod(config, targetRequest); } //copy the target response headers to our response setupResponseHeaders(targetRequest, hsResponse); InputStream originalResponseStream = targetRequest.getResponseBodyAsStream(); //the body might be null, i.e. for responses with cache-headers which leave out the body if (originalResponseStream != null) { OutputStream responseStream = hsResponse.getOutputStream(); copyStream(originalResponseStream, responseStream); } log.info("set up response, result code was " + result); }
From source file:org.zaproxy.zap.extension.ascanrulesAlpha.CloudMetadataScanner.java
private static HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body, HttpMethodParams params) throws URIException { HttpMethod httpMethod = new ZapGetMethod(); httpMethod.setURI(header.getURI());//from ww w . j a v a2s . c o m httpMethod.setParams(params); params.setVersion(HttpVersion.HTTP_1_1); String msg = header.getHeadersAsString(); String[] split = Pattern.compile("\\r\\n", Pattern.MULTILINE).split(msg); String token = null; String name = null; String value = null; int pos = 0; for (int i = 0; i < split.length; i++) { token = split[i]; if (token.equals("")) { continue; } if ((pos = token.indexOf(":")) < 0) { return null; } name = token.substring(0, pos).trim(); value = token.substring(pos + 1).trim(); httpMethod.addRequestHeader(name, value); } if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) { EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod; post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes())); } httpMethod.setFollowRedirects(false); return httpMethod; }
From source file:smartrics.jmeter.sampler.RestSampler.java
/** * Set up the PUT/POST data./* w w w .j av a2 s .c o m*/ * * <b>TODO</b>: should parse request headers and pass the Content-Type. For * now it will always assume text/xml */ private String sendData(EntityEnclosingMethod method) throws IOException { method.setRequestEntity(new MyRequestEntity(getRequestBody())); return getRequestBody(); }