use of org.apache.commons.httpclient.methods.RequestEntity 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.RequestEntity in project camel by apache.
the class HttpProducer method createRequestEntity.
/**
* Creates a holder object for the data to send to the remote server.
*
* @param exchange the exchange with the IN message with data to send
* @return the data holder
* @throws CamelExchangeException is thrown if error creating RequestEntity
*/
protected RequestEntity createRequestEntity(Exchange exchange) throws CamelExchangeException {
Message in = exchange.getIn();
if (in.getBody() == null) {
return null;
}
RequestEntity answer = in.getBody(RequestEntity.class);
if (answer == null) {
try {
Object data = in.getBody();
if (data != null) {
String contentType = ExchangeHelper.getContentType(exchange);
if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
if (!getEndpoint().getComponent().isAllowJavaSerializedObject()) {
throw new CamelExchangeException("Content-type " + HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed", exchange);
}
// serialized java object
Serializable obj = in.getMandatoryBody(Serializable.class);
// write object to output stream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
HttpHelper.writeObjectToStream(bos, obj);
answer = new ByteArrayRequestEntity(bos.toByteArray(), HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
IOHelper.close(bos);
} else if (data instanceof File || data instanceof GenericFile) {
// file based (could potentially also be a FTP file etc)
File file = in.getBody(File.class);
if (file != null) {
answer = new FileRequestEntity(file, contentType);
}
} else if (data instanceof String) {
// be a bit careful with String as any type can most likely be converted to String
// so we only do an instanceof check and accept String if the body is really a String
// do not fallback to use the default charset as it can influence the request
// (for example application/x-www-form-urlencoded forms being sent)
String charset = IOHelper.getCharsetName(exchange, false);
answer = new StringRequestEntity((String) data, contentType, charset);
}
// fallback as input stream
if (answer == null) {
// force the body as an input stream since this is the fallback
InputStream is = in.getMandatoryBody(InputStream.class);
answer = new InputStreamRequestEntity(is, contentType);
}
}
} catch (UnsupportedEncodingException e) {
throw new CamelExchangeException("Error creating RequestEntity from message body", exchange, e);
} catch (IOException e) {
throw new CamelExchangeException("Error serializing message body", exchange, e);
}
}
return answer;
}
use of org.apache.commons.httpclient.methods.RequestEntity in project pinot by linkedin.
the class FileUploadUtils method sendSegmentJsonImpl.
public static int sendSegmentJsonImpl(final String host, final String port, final JSONObject segmentJson) {
PostMethod postMethod = null;
try {
RequestEntity requestEntity = new StringRequestEntity(segmentJson.toString(), ContentType.APPLICATION_JSON.getMimeType(), ContentType.APPLICATION_JSON.getCharset().name());
postMethod = new PostMethod("http://" + host + ":" + port + "/" + SEGMENTS_PATH);
postMethod.setRequestEntity(requestEntity);
postMethod.setRequestHeader(UPLOAD_TYPE, FileUploadType.JSON.toString());
int statusCode = FILE_UPLOAD_HTTP_CLIENT.executeMethod(postMethod);
if (statusCode >= 400) {
String errorString = "POST Status Code: " + statusCode + "\n";
if (postMethod.getResponseHeader("Error") != null) {
errorString += "ServletException: " + postMethod.getResponseHeader("Error").getValue();
}
throw new HttpException(errorString);
}
return statusCode;
} catch (Exception e) {
LOGGER.error("Caught exception while sending json: {}", segmentJson.toString(), e);
Utils.rethrowException(e);
throw new AssertionError("Should not reach this");
} finally {
if (postMethod != null) {
postMethod.releaseConnection();
}
}
}
use of org.apache.commons.httpclient.methods.RequestEntity 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.RequestEntity in project camel by apache.
the class JaxbFallbackTypeConverterTest method createRouteBuilder.
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
// setup the camel property for the PrettyPrint
context.getProperties().put(FallbackTypeConverter.PRETTY_PRINT, "false");
from("direct:start").process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
RequestEntity entity = in.getBody(RequestEntity.class);
assertNull("We should not get the entity here", entity);
InputStream is = in.getMandatoryBody(InputStream.class);
// make sure we can get the InputStream rightly.
exchange.getOut().setBody(is);
}
});
}
};
}
Aggregations