List of usage examples for org.apache.commons.httpclient HttpMethod setParams
public abstract void setParams(HttpMethodParams paramHttpMethodParams);
From source file:com.starit.diamond.client.impl.DefaultDiamondSubscriber.java
private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut, HttpMethod httpMethod) { if (skipContentCache && null != cacheData) { if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) { httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader()); }//from w w w .ja v a2s. c o m if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) { httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5()); } } // appName if (null != this.appName) { httpMethod.addRequestHeader(Constants.APPNAME, this.appName); } httpMethod.addRequestHeader(Constants.CLIENT_VERSION_HEADER, Constants.CLIENT_VERSION); httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate"); // HttpMethod? HttpMethodParams params = new HttpMethodParams(); params.setSoTimeout((int) onceTimeOut); // /////////////////////// httpMethod.setParams(params); httpClient.getHostConfiguration().setHost( diamondConfigure.getDomainNameList().get(this.domainNamePos.get()), diamondConfigure.getPort()); }
From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java
protected void executeMethod(HttpClient httpClient, MessageContext msgContext, URL url, HttpMethod method) throws IOException { HostConfiguration config = this.getHostConfiguration(httpClient, msgContext, url); // set the custom headers, if available addCustomHeaders(method, msgContext); // add compression headers if needed if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) { method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP); }/*from w w w .ja v a 2 s.c o m*/ if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP); } if (msgContext.getProperty(HTTPConstants.HTTP_METHOD_PARAMS) != null) { HttpMethodParams params = (HttpMethodParams) msgContext.getProperty(HTTPConstants.HTTP_METHOD_PARAMS); method.setParams(params); } String cookiePolicy = (String) msgContext.getProperty(HTTPConstants.COOKIE_POLICY); if (cookiePolicy != null) { method.getParams().setCookiePolicy(cookiePolicy); } HttpState httpState = (HttpState) msgContext.getProperty(HTTPConstants.CACHED_HTTP_STATE); setTimeouts(msgContext, method); httpClient.executeMethod(config, method, httpState); }
From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java
protected void setParameters(HttpMethod method) { HttpMethodConfiguration config = httpConfiguration == null ? null : httpConfiguration.getMethodConfiguration(method); if (config != null) { HttpMethodParams params = config.asMethodParams(method.getParams()); if (params != null) { method.setParams(params); }// w ww.ja v a 2 s .co m } if (config == null || config.getConnectionTimeout() == HttpMethodConfiguration.DEFAULT_CONNECTION_TIMEOUT) { method.getParams().setSoTimeout(getTimeout()); } }
From source file:org.eclipse.orion.server.cf.utils.HttpUtil.java
public static void configureHttpMethod(HttpMethod method, Target target) throws JSONException { method.addRequestHeader(new Header("Accept", "application/json")); method.addRequestHeader(new Header("Content-Type", "application/json")); //set default socket timeout for connection HttpMethodParams params = method.getParams(); params.setSoTimeout(DEFAULT_SOCKET_TIMEOUT); method.setParams(params); if (target.getCloud().getAccessToken() != null) method.addRequestHeader(new Header("Authorization", "bearer " + target.getCloud().getAccessToken().getString("access_token"))); }
From source file:org.eclipse.orion.server.cf.utils.HttpUtil.java
public static void configureHttpMethod(HttpMethod method, Cloud cloud) throws JSONException { method.addRequestHeader(new Header("Accept", "application/json")); method.addRequestHeader(new Header("Content-Type", "application/json")); //set default socket timeout for connection HttpMethodParams params = method.getParams(); params.setSoTimeout(DEFAULT_SOCKET_TIMEOUT); method.setParams(params); if (cloud.getAccessToken() != null) method.addRequestHeader(/*from w w w . jav a2s . c o m*/ new Header("Authorization", "bearer " + cloud.getAccessToken().getString("access_token"))); }
From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java
@Override public Object transformMessage(MuleMessage msg, String outputEncoding) throws TransformerException { String method = detectHttpMethod(msg); try {/* w w w . ja v a2 s .c o m*/ HttpMethod httpMethod; if (HttpConstants.METHOD_GET.equals(method)) { httpMethod = createGetMethod(msg, outputEncoding); } else if (HttpConstants.METHOD_POST.equalsIgnoreCase(method)) { httpMethod = createPostMethod(msg, outputEncoding); } else if (HttpConstants.METHOD_PUT.equalsIgnoreCase(method)) { httpMethod = createPutMethod(msg, outputEncoding); } else if (HttpConstants.METHOD_DELETE.equalsIgnoreCase(method)) { httpMethod = createDeleteMethod(msg); } else if (HttpConstants.METHOD_HEAD.equalsIgnoreCase(method)) { httpMethod = createHeadMethod(msg); } else if (HttpConstants.METHOD_OPTIONS.equalsIgnoreCase(method)) { httpMethod = createOptionsMethod(msg); } else if (HttpConstants.METHOD_TRACE.equalsIgnoreCase(method)) { httpMethod = createTraceMethod(msg); } else if (HttpConstants.METHOD_PATCH.equalsIgnoreCase(method)) { httpMethod = createPatchMethod(msg); } else { throw new TransformerException(HttpMessages.unsupportedMethod(method)); } // Allow the user to set HttpMethodParams as an object on the message final HttpMethodParams params = (HttpMethodParams) msg .removeProperty(HttpConnector.HTTP_PARAMS_PROPERTY, PropertyScope.OUTBOUND); if (params != null) { httpMethod.setParams(params); } else { // TODO we should probably set other properties here final String httpVersion = msg.getOutboundProperty(HttpConnector.HTTP_VERSION_PROPERTY, HttpConstants.HTTP11); if (HttpConstants.HTTP10.equals(httpVersion)) { httpMethod.getParams().setVersion(HttpVersion.HTTP_1_0); } else { httpMethod.getParams().setVersion(HttpVersion.HTTP_1_1); } } setHeaders(httpMethod, msg); return httpMethod; } catch (final Exception e) { throw new TransformerException(this, e); } }
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>// www .ja v a2s . 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 "); }
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 w w w . ja v a 2 s . c om*/ 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; }