List of usage examples for org.apache.commons.httpclient.methods EntityEnclosingMethod setContentChunked
public void setContentChunked(boolean paramBoolean)
From source file:com.vmware.aurora.vc.VcFileManager.java
static private void uploadFileWork(String url, boolean isPost, File file, String contentType, String cookie, ProgressListener listener) throws Exception { EntityEnclosingMethod method; final RequestEntity entity = new ProgressListenerRequestEntity(file, contentType, listener); if (isPost) { method = new PostMethod(url); method.setContentChunked(true); } else {//from w w w. ja v a2s .c om method = new PutMethod(url); method.addRequestHeader("Cookie", cookie); method.setContentChunked(false); HttpMethodParams params = new HttpMethodParams(); params.setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); method.setParams(params); } method.setRequestEntity(entity); logger.info("upload " + file + " to " + url); long t1 = System.currentTimeMillis(); boolean ok = false; try { HttpClient httpClient = new HttpClient(); int statusCode = httpClient.executeMethod(method); String response = method.getResponseBodyAsString(100); logger.debug("status: " + statusCode + " response: " + response); if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) { throw new Exception("Http post failed"); } method.releaseConnection(); ok = true; } finally { if (!ok) { method.abort(); } } long t2 = System.currentTimeMillis(); logger.info("upload " + file + " done in " + (t2 - t1) + " ms"); }
From source file:com.eviware.soapui.impl.wsdl.submit.filters.PostPackagingRequestFilter.java
@Override public void filterAbstractHttpRequest(SubmitContext context, AbstractHttpRequest<?> request) { ExtendedHttpMethod httpMethod = (ExtendedHttpMethod) context .getProperty(BaseHttpRequestTransport.HTTP_METHOD); Settings settings = request.getSettings(); // chunking?//from w ww . ja va 2s . c o m if (httpMethod.getParams().getVersion().equals(HttpVersion.HTTP_1_1) && httpMethod instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = ((EntityEnclosingMethod) httpMethod); long limit = settings.getLong(HttpSettings.CHUNKING_THRESHOLD, -1); RequestEntity requestEntity = entityEnclosingMethod.getRequestEntity(); entityEnclosingMethod.setContentChunked( limit >= 0 && requestEntity != null ? requestEntity.getContentLength() > limit : false); } }
From source file:fedora.test.integration.TestLargeDatastreams.java
private String upload() throws Exception { String url = fedoraClient.getUploadURL(); EntityEnclosingMethod httpMethod = new PostMethod(url); httpMethod.setDoAuthentication(true); httpMethod.getParams().setParameter("Connection", "Keep-Alive"); httpMethod.setContentChunked(true); Part[] parts = { new FilePart("file", new SizedPartSource()) }; httpMethod.setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams())); HttpClient client = fedoraClient.getHttpClient(); try {//from w ww . ja v a 2 s.c o m int status = client.executeMethod(httpMethod); String response = new String(httpMethod.getResponseBody()); if (status != HttpStatus.SC_CREATED) { throw new IOException("Upload failed: " + HttpStatus.getStatusText(status) + ": " + replaceNewlines(response, " ")); } else { response = response.replaceAll("\r", "").replaceAll("\n", ""); return response; } } finally { httpMethod.releaseConnection(); } }
From source file:com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.java
@Override public void executeMethod(final HttpMethod method, final ClientRequest cr) { final Map<String, Object> props = cr.getProperties(); method.setDoAuthentication(true);/* ww w .j ava 2s .c o m*/ final HttpMethodParams methodParams = method.getParams(); // Set the handle cookies property if (!cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES)) { methodParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); } // Set the interactive and credential provider properties if (cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_INTERACTIVE)) { CredentialsProvider provider = (CredentialsProvider) props .get(ApacheHttpClientConfig.PROPERTY_CREDENTIALS_PROVIDER); if (provider == null) { provider = DEFAULT_CREDENTIALS_PROVIDER; } methodParams.setParameter(CredentialsProvider.PROVIDER, provider); } else { methodParams.setParameter(CredentialsProvider.PROVIDER, null); } // Set the read timeout final Integer readTimeout = (Integer) props.get(ApacheHttpClientConfig.PROPERTY_READ_TIMEOUT); if (readTimeout != null) { methodParams.setSoTimeout(readTimeout); } if (method instanceof EntityEnclosingMethod) { final EntityEnclosingMethod entMethod = (EntityEnclosingMethod) method; if (cr.getEntity() != null) { final RequestEntityWriter re = getRequestEntityWriter(cr); final Integer chunkedEncodingSize = (Integer) props .get(ApacheHttpClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE); if (chunkedEncodingSize != null) { // There doesn't seems to be a way to set the chunk size. entMethod.setContentChunked(true); // It is not possible for a MessageBodyWriter to modify // the set of headers before writing out any bytes to // the OutputStream // This makes it impossible to use the multipart // writer that modifies the content type to add a boundary // parameter writeOutBoundHeaders(cr.getHeaders(), method); // Do not buffer the request entity when chunked encoding is // set entMethod.setRequestEntity(new RequestEntity() { @Override public boolean isRepeatable() { return false; } @Override public void writeRequest(OutputStream out) throws IOException { re.writeRequestEntity(out); } @Override public long getContentLength() { return re.getSize(); } @Override public String getContentType() { return re.getMediaType().toString(); } }); } else { entMethod.setContentChunked(false); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { re.writeRequestEntity(new CommittingOutputStream(baos) { @Override protected void commit() throws IOException { writeOutBoundHeaders(cr.getMetadata(), method); } }); } catch (IOException ex) { throw new ClientHandlerException(ex); } final byte[] content = baos.toByteArray(); entMethod.setRequestEntity(new RequestEntity() { @Override public boolean isRepeatable() { return true; } @Override public void writeRequest(OutputStream out) throws IOException { out.write(content); } @Override public long getContentLength() { return content.length; } @Override public String getContentType() { return re.getMediaType().toString(); } }); } } else { writeOutBoundHeaders(cr.getHeaders(), method); } } else { writeOutBoundHeaders(cr.getHeaders(), method); // Follow redirects method.setFollowRedirects(cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_FOLLOW_REDIRECTS)); } try { httpClient.executeMethod(getHostConfiguration(httpClient, props), method, getHttpState(props)); } catch (Exception e) { method.releaseConnection(); throw new ClientHandlerException(e); } }
From source file:fedora.test.api.TestRESTAPI.java
private HttpResponse putOrPost(String method, Object requestContent, boolean authenticate) throws Exception { if (url == null || url.length() == 0) { throw new IllegalArgumentException("url must be a non-empty value"); } else if (!(url.startsWith("http://") || url.startsWith("https://"))) { url = getBaseURL() + url;/* w w w .j a v a 2 s. com*/ } EntityEnclosingMethod httpMethod = null; try { if (method.equals("PUT")) { httpMethod = new PutMethod(url); } else if (method.equals("POST")) { httpMethod = new PostMethod(url); } else { throw new IllegalArgumentException("method must be one of PUT or POST."); } httpMethod.setDoAuthentication(authenticate); httpMethod.getParams().setParameter("Connection", "Keep-Alive"); if (requestContent != null) { httpMethod.setContentChunked(chunked); if (requestContent instanceof String) { httpMethod.setRequestEntity( new StringRequestEntity((String) requestContent, "text/xml", "utf-8")); } else if (requestContent instanceof File) { Part[] parts = { new StringPart("param_name", "value"), new FilePart(((File) requestContent).getName(), (File) requestContent) }; httpMethod.setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams())); } else { throw new IllegalArgumentException("requestContent must be a String or File"); } } getClient(authenticate).executeMethod(httpMethod); return new HttpResponse(httpMethod); } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java
/** * create and initialize the http method. * Http Headers that may been passed in the params are not set in this method. * Headers will be automatically set by HttpClient. * See usages of HostParams.DEFAULT_HEADERS * See org.apache.commons.httpclient.HttpMethodDirector#executeMethod(org.apache.commons.httpclient.HttpMethod) *///w w w.j a v a2s. com protected HttpMethod prepareHttpMethod(BindingOperation opBinding, String verb, Map<String, Element> partValues, Map<String, Node> headers, final String rootUri, HttpParams params) throws UnsupportedEncodingException { if (log.isDebugEnabled()) log.debug("Preparing http request..."); // convenience variables... BindingInput bindingInput = opBinding.getBindingInput(); HTTPOperation httpOperation = (HTTPOperation) WsdlUtils.getOperationExtension(opBinding); MIMEContent content = WsdlUtils.getMimeContent(bindingInput.getExtensibilityElements()); String contentType = content == null ? null : content.getType(); boolean useUrlEncoded = WsdlUtils.useUrlEncoded(bindingInput) || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equalsIgnoreCase(contentType); boolean useUrlReplacement = WsdlUtils.useUrlReplacement(bindingInput); // the http method to be built and returned HttpMethod method = null; // the 4 elements the http method may be made of String relativeUri = httpOperation.getLocationURI(); String queryPath = null; RequestEntity requestEntity; String encodedParams = null; // ODE supports uri template in both port and operation location. // so assemble the final url *before* replacement String completeUri = rootUri; if (StringUtils.isNotEmpty(relativeUri)) { completeUri = completeUri + (completeUri.endsWith("/") || relativeUri.startsWith("/") ? "" : "/") + relativeUri; } if (useUrlReplacement) { // insert part values in the url completeUri = new UrlReplacementTransformer().transform(completeUri, partValues); } else if (useUrlEncoded) { // encode part values encodedParams = new URLEncodedTransformer().transform(partValues); } // http-client api is not really neat // something similar to the following would save some if/else manipulations. // But we have to deal with it as-is. // // method = new Method(verb); // method.setRequestEnity(..) // etc... if ("GET".equalsIgnoreCase(verb) || "DELETE".equalsIgnoreCase(verb)) { if ("GET".equalsIgnoreCase(verb)) { method = new GetMethod(); } else if ("DELETE".equalsIgnoreCase(verb)) { method = new DeleteMethod(); } method.getParams().setDefaults(params); if (useUrlEncoded) { queryPath = encodedParams; } // Let http-client manage the redirection // see org.apache.commons.httpclient.params.HttpClientParams.MAX_REDIRECTS // default is 100 method.setFollowRedirects(true); } else if ("POST".equalsIgnoreCase(verb) || "PUT".equalsIgnoreCase(verb)) { if ("POST".equalsIgnoreCase(verb)) { method = new PostMethod(); } else if ("PUT".equalsIgnoreCase(verb)) { method = new PutMethod(); } method.getParams().setDefaults(params); // some body-building... final String contentCharset = method.getParams().getContentCharset(); if (log.isDebugEnabled()) log.debug("Content-Type [" + contentType + "] Charset [" + contentCharset + "]"); if (useUrlEncoded) { requestEntity = new StringRequestEntity(encodedParams, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE, contentCharset); } else { // get the part to be put in the body Part part = opBinding.getOperation().getInput().getMessage().getPart(content.getPart()); Element partValue = partValues.get(part.getName()); if (part.getElementName() == null) { String errMsg = "XML Types are not supported. Parts must use elements."; if (log.isErrorEnabled()) log.error(errMsg); throw new RuntimeException(errMsg); } else if (HttpUtils.isXml(contentType)) { if (log.isDebugEnabled()) log.debug("Content-Type [" + contentType + "] equivalent to 'text/xml'"); // stringify the first element String xmlString = DOMUtils.domToString(DOMUtils.getFirstChildElement(partValue)); requestEntity = new StringRequestEntity(xmlString, contentType, contentCharset); } else { if (log.isDebugEnabled()) log.debug("Content-Type [" + contentType + "] NOT equivalent to 'text/xml'. The text content of part value will be sent as text"); // encoding conversion is managed by StringRequestEntity if necessary requestEntity = new StringRequestEntity(DOMUtils.getTextContent(partValue), contentType, contentCharset); } } // cast safely, PUT and POST are subclasses of EntityEnclosingMethod final EntityEnclosingMethod enclosingMethod = (EntityEnclosingMethod) method; enclosingMethod.setRequestEntity(requestEntity); enclosingMethod .setContentChunked(params.getBooleanParameter(Properties.PROP_HTTP_REQUEST_CHUNK, false)); } else { // should not happen because of HttpBindingValidator, but never say never throw new IllegalArgumentException("Unsupported HTTP method: " + verb); } method.setPath(completeUri); // assumes that the path is properly encoded (URL safe). method.setQueryString(queryPath); // set headers setHttpRequestHeaders(method, opBinding, partValues, headers, params); return method; }
From source file:org.elasticsearch.hadoop.rest.commonshttp.CommonsHttpTransport.java
@Override public Response execute(Request request) throws IOException { HttpMethod http = null;//from ww w . ja va2 s .c om switch (request.method()) { case DELETE: http = new DeleteMethodWithBody(); break; case HEAD: http = new HeadMethod(); break; case GET: http = (request.body() == null ? new GetMethod() : new GetMethodWithBody()); break; case POST: http = new PostMethod(); break; case PUT: http = new PutMethod(); break; default: throw new EsHadoopTransportException("Unknown request method " + request.method()); } CharSequence uri = request.uri(); if (StringUtils.hasText(uri)) { http.setURI(new URI(escapeUri(uri.toString(), settings.getNetworkSSLEnabled()), false)); } // NB: initialize the path _after_ the URI otherwise the path gets reset to / http.setPath(prefixPath(request.path().toString())); try { // validate new URI uri = http.getURI().toString(); } catch (URIException uriex) { throw new EsHadoopTransportException("Invalid target URI " + request, uriex); } CharSequence params = request.params(); if (StringUtils.hasText(params)) { http.setQueryString(params.toString()); } ByteSequence ba = request.body(); if (ba != null && ba.length() > 0) { if (!(http instanceof EntityEnclosingMethod)) { throw new IllegalStateException(String.format("Method %s cannot contain body - implementation bug", request.method().name())); } EntityEnclosingMethod entityMethod = (EntityEnclosingMethod) http; entityMethod.setRequestEntity(new BytesArrayRequestEntity(ba)); entityMethod.setContentChunked(false); } // when tracing, log everything if (log.isTraceEnabled()) { log.trace(String.format("Tx %s[%s]@[%s][%s] w/ payload [%s]", proxyInfo, request.method().name(), httpInfo, request.path(), request.body())); } long start = System.currentTimeMillis(); try { client.executeMethod(http); } finally { stats.netTotalTime += (System.currentTimeMillis() - start); } if (log.isTraceEnabled()) { Socket sk = ReflectionUtils.invoke(GET_SOCKET, conn, (Object[]) null); String addr = sk.getLocalAddress().getHostAddress(); log.trace(String.format("Rx %s@[%s] [%s-%s] [%s]", proxyInfo, addr, http.getStatusCode(), HttpStatus.getStatusText(http.getStatusCode()), http.getResponseBodyAsString())); } // the request URI is not set (since it is retried across hosts), so use the http info instead for source return new SimpleResponse(http.getStatusCode(), new ResponseInputStream(http), httpInfo); }
From source file:org.mule.transport.http.HttpClientMessageDispatcher.java
protected HttpMethod createEntityMethod(MuleEvent event, Object body, EntityEnclosingMethod postMethod) throws TransformerException { HttpMethod httpMethod;// ww w . j a v a 2 s .co m if (body instanceof String) { httpMethod = (HttpMethod) sendTransformer.transform(body.toString()); } else if (body instanceof byte[]) { byte[] buffer = event.transformMessage(DataType.BYTE_ARRAY_DATA_TYPE); postMethod.setRequestEntity(new ByteArrayRequestEntity(buffer, event.getEncoding())); httpMethod = postMethod; } else { if (!(body instanceof OutputHandler)) { body = event.transformMessage(DataTypeFactory.create(OutputHandler.class)); } OutputHandler outputHandler = (OutputHandler) body; postMethod.setRequestEntity(new StreamPayloadRequestEntity(outputHandler, event)); postMethod.setContentChunked(true); httpMethod = postMethod; } return httpMethod; }