use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project camel by apache.
the class HttpProducer method createMethod.
/**
* Creates the HttpMethod to use to call the remote server, either its GET or POST.
*
* @param exchange the exchange
* @return the created method as either GET or POST
* @throws CamelExchangeException is thrown if error creating RequestEntity
*/
@SuppressWarnings("deprecation")
protected HttpMethod createMethod(Exchange exchange) throws Exception {
// creating the url to use takes 2-steps
String url = HttpHelper.createURL(exchange, getEndpoint());
URI uri = HttpHelper.createURI(exchange, url, getEndpoint());
// get the url and query string from the uri
url = uri.toASCIIString();
String queryString = uri.getRawQuery();
// execute any custom url rewrite
String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this);
if (rewriteUrl != null) {
// update url and query string from the rewritten url
url = rewriteUrl;
uri = new URI(url);
// use raw query to have uri decimal encoded which http client requires
queryString = uri.getRawQuery();
}
// remove query string as http client does not accept that
if (url.indexOf('?') != -1) {
url = url.substring(0, url.indexOf('?'));
}
// create http holder objects for the request
RequestEntity requestEntity = createRequestEntity(exchange);
String methodName = HttpHelper.createMethod(exchange, getEndpoint(), requestEntity != null).name();
HttpMethods methodsToUse = HttpMethods.valueOf(methodName);
HttpMethod method = methodsToUse.createMethod(url);
if (queryString != null) {
// need to encode query string
queryString = UnsafeUriCharactersEncoder.encode(queryString);
method.setQueryString(queryString);
}
LOG.trace("Using URL: {} with method: {}", url, method);
if (methodsToUse.isEntityEnclosing()) {
((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
if (requestEntity != null && requestEntity.getContentType() == null) {
LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange);
}
}
// there must be a host on the method
if (method.getHostConfiguration().getHost() == null) {
throw new IllegalArgumentException("Invalid uri: " + url + ". If you are forwarding/bridging http endpoints, then enable the bridgeEndpoint option on the endpoint: " + getEndpoint());
}
return method;
}
use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project pinot by linkedin.
the class FileUploadUtils method sendSegmentUriImpl.
private static int sendSegmentUriImpl(final String host, final String port, final String uri) {
SendFileMethod httpMethod = SendFileMethod.POST;
EntityEnclosingMethod method = null;
try {
method = httpMethod.forUri("http://" + host + ":" + port + "/" + SEGMENTS_PATH);
method.setRequestHeader(UPLOAD_TYPE, FileUploadType.URI.toString());
method.setRequestHeader(DOWNLOAD_URI, uri);
FILE_UPLOAD_HTTP_CLIENT.executeMethod(method);
if (method.getStatusCode() >= 400) {
String errorString = "POST Status Code: " + method.getStatusCode() + "\n";
if (method.getResponseHeader("Error") != null) {
errorString += "ServletException: " + method.getResponseHeader("Error").getValue();
}
throw new HttpException(errorString);
}
return method.getStatusCode();
} catch (Exception e) {
LOGGER.error("Caught exception while sending uri: {}", uri, e);
Utils.rethrowException(e);
throw new AssertionError("Should not reach this");
} finally {
if (method != null) {
method.releaseConnection();
}
}
}
use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project pinot by linkedin.
the class FileUploadUtils method sendFile.
public static int sendFile(final String host, final String port, final String path, final String fileName, final InputStream inputStream, final long lengthInBytes, SendFileMethod httpMethod) {
EntityEnclosingMethod method = null;
try {
method = httpMethod.forUri("http://" + host + ":" + port + "/" + path);
Part[] parts = { new FilePart(fileName, new PartSource() {
@Override
public long getLength() {
return lengthInBytes;
}
@Override
public String getFileName() {
return fileName;
}
@Override
public InputStream createInputStream() throws IOException {
return new BufferedInputStream(inputStream);
}
}) };
method.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams()));
FILE_UPLOAD_HTTP_CLIENT.executeMethod(method);
if (method.getStatusCode() >= 400) {
String errorString = "POST Status Code: " + method.getStatusCode() + "\n";
if (method.getResponseHeader("Error") != null) {
errorString += "ServletException: " + method.getResponseHeader("Error").getValue();
}
throw new HttpException(errorString);
}
return method.getStatusCode();
} catch (Exception e) {
LOGGER.error("Caught exception while sending file: {}", fileName, e);
Utils.rethrowException(e);
throw new AssertionError("Should not reach this");
} finally {
if (method != null) {
method.releaseConnection();
}
}
}
use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project pinpoint by naver.
the class HttpMethodBaseExecuteMethodInterceptor method recordEntity.
private void recordEntity(HttpMethod httpMethod, Trace trace) {
if (httpMethod instanceof EntityEnclosingMethod) {
final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;
final RequestEntity entity = entityEnclosingMethod.getRequestEntity();
if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
if (entitySampler.isSampling()) {
try {
String entityValue;
String charSet = entityEnclosingMethod.getRequestCharSet();
if (charSet == null || charSet.isEmpty()) {
charSet = HttpConstants.DEFAULT_CONTENT_CHARSET;
}
if (entity instanceof ByteArrayRequestEntity || entity instanceof StringRequestEntity) {
entityValue = entityUtilsToString(entity, charSet);
} else {
entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")";
}
final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
recorder.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, entityValue);
} catch (Exception e) {
logger.debug("HttpEntityEnclosingRequest entity record fail. Caused:{}", e.getMessage(), e);
}
}
}
}
}
use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project openhab1-addons by openhab.
the class AbstractRequest method executeUrl.
/**
* Executes the given <code>url</code> with the given <code>httpMethod</code>. In the case of httpMethods that do
* not support automatic redirection, manually handle the HTTP temporary redirect (307) and retry with the new URL.
*
* @param httpMethod
* the HTTP method to use
* @param url
* the url to execute (in milliseconds)
* @param contentString
* the content to be sent to the given <code>url</code> or <code>null</code> if no content should be
* sent.
* @param contentType
* the content type of the given <code>contentString</code>
* @return the response body or <code>NULL</code> when the request went wrong
*/
protected final String executeUrl(final String httpMethod, final String url, final String contentString, final String contentType) {
HttpClient client = new HttpClient();
HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
method.getParams().setSoTimeout(httpRequestTimeout);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
for (String httpHeaderKey : HTTP_HEADERS.stringPropertyNames()) {
method.addRequestHeader(new Header(httpHeaderKey, HTTP_HEADERS.getProperty(httpHeaderKey)));
}
// add content if a valid method is given ...
if (method instanceof EntityEnclosingMethod && contentString != null) {
EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
InputStream content = new ByteArrayInputStream(contentString.getBytes());
eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
}
if (logger.isDebugEnabled()) {
try {
logger.trace("About to execute '" + method.getURI().toString() + "'");
} catch (URIException e) {
logger.trace(e.getMessage());
}
}
try {
int statusCode = client.executeMethod(method);
if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
// perfectly fine but we cannot expect any answer...
return null;
}
// Manually handle 307 redirects with a little tail recursion
if (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
Header[] headers = method.getResponseHeaders("Location");
String newUrl = headers[headers.length - 1].getValue();
return executeUrl(httpMethod, newUrl, contentString, contentType);
}
if (statusCode != HttpStatus.SC_OK) {
logger.warn("Method failed: " + method.getStatusLine());
}
InputStream tmpResponseStream = method.getResponseBodyAsStream();
Header encodingHeader = method.getResponseHeader("Content-Encoding");
if (encodingHeader != null) {
for (HeaderElement ehElem : encodingHeader.getElements()) {
if (ehElem.toString().matches(".*gzip.*")) {
tmpResponseStream = new GZIPInputStream(tmpResponseStream);
logger.trace("GZipped InputStream from {}", url);
} else if (ehElem.toString().matches(".*deflate.*")) {
tmpResponseStream = new InflaterInputStream(tmpResponseStream);
logger.trace("Deflated InputStream from {}", url);
}
}
}
String responseBody = IOUtils.toString(tmpResponseStream);
if (!responseBody.isEmpty()) {
logger.trace(responseBody);
}
return responseBody;
} catch (HttpException he) {
logger.error("Fatal protocol violation: {}", he.toString());
} catch (IOException ioe) {
logger.error("Fatal transport error: {}", ioe.toString());
} finally {
method.releaseConnection();
}
return null;
}
Aggregations