use of org.apache.commons.httpclient.params.HttpMethodParams in project camel by apache.
the class HttpProducer method process.
public void process(Exchange exchange) throws Exception {
// if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
// duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
Map<String, Object> skipRequestHeaders = null;
if (getEndpoint().isBridgeEndpoint()) {
exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
if (queryString != null) {
skipRequestHeaders = URISupport.parseQuery(queryString, false, true);
}
// Need to remove the Host key as it should be not used
exchange.getIn().getHeaders().remove("host");
}
HttpMethod method = createMethod(exchange);
Message in = exchange.getIn();
String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class);
if (httpProtocolVersion != null) {
// set the HTTP protocol version
HttpMethodParams params = method.getParams();
params.setVersion(HttpVersion.parse(httpProtocolVersion));
}
HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();
// propagate headers as HTTP headers
for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
String key = entry.getKey();
Object headerValue = in.getHeader(key);
if (headerValue != null) {
// use an iterator as there can be multiple values. (must not use a delimiter, and allow empty values)
final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true);
// the value to add as request header
final List<String> values = new ArrayList<String>();
// should be combined into a single value
while (it.hasNext()) {
String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());
// as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
continue;
}
if (value != null && strategy != null && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
values.add(value);
}
}
// add the value(s) as a http request header
if (values.size() > 0) {
// use the default toString of a ArrayList to create in the form [xxx, yyy]
// if multi valued, for a single value, then just output the value as is
String s = values.size() > 1 ? values.toString() : values.get(0);
method.addRequestHeader(key, s);
}
}
}
if (getEndpoint().getCookieHandler() != null) {
// disable the per endpoint cookie handling
method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
Map<String, List<String>> cookieHeaders = getEndpoint().getCookieHandler().loadCookies(exchange, new URI(method.getURI().getEscapedURI()));
for (Map.Entry<String, List<String>> entry : cookieHeaders.entrySet()) {
String key = entry.getKey();
if (entry.getValue().size() > 0) {
// use the default toString of a ArrayList to create in the form [xxx, yyy]
// if multi valued, for a single value, then just output the value as is
String s = entry.getValue().size() > 1 ? entry.getValue().toString() : entry.getValue().get(0);
method.addRequestHeader(key, s);
}
}
}
if (getEndpoint().isConnectionClose()) {
method.addRequestHeader("Connection", "close");
}
// lets store the result in the output message.
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Executing http {} method: {}", method.getName(), method.getURI().toString());
}
int responseCode = executeMethod(method);
LOG.debug("Http responseCode: {}", responseCode);
if (!throwException) {
// if we do not use failed exception then populate response for all response codes
populateResponse(exchange, method, in, strategy, responseCode);
} else {
boolean ok = HttpHelper.isStatusCodeOk(responseCode, getEndpoint().getOkStatusCodeRange());
if (ok) {
// only populate response for OK response
populateResponse(exchange, method, in, strategy, responseCode);
} else {
// operation failed so populate exception to throw
throw populateHttpOperationFailedException(exchange, method, responseCode);
}
}
} finally {
method.releaseConnection();
}
}
use of org.apache.commons.httpclient.params.HttpMethodParams in project camel by apache.
the class MultiPartFormTest method createMultipartRequestEntity.
private RequestEntity createMultipartRequestEntity() throws Exception {
File file = new File("src/main/resources/META-INF/NOTICE.txt");
Part[] parts = { new StringPart("comment", "A binary file of some kind"), new FilePart(file.getName(), file) };
return new MultipartRequestEntity(parts, new HttpMethodParams());
}
use of org.apache.commons.httpclient.params.HttpMethodParams in project hadoop by apache.
the class SwiftRestClient method perform.
/**
* Performs the HTTP request, validates the response code and returns
* the received data. HTTP Status codes are converted into exceptions.
* @param reason why is this operation taking place. Used for statistics
* @param uri URI to source
* @param processor HttpMethodProcessor
* @param <M> method
* @param <R> result type
* @return result of HTTP request
* @throws IOException IO problems
* @throws SwiftBadRequestException the status code indicated "Bad request"
* @throws SwiftInvalidResponseException the status code is out of range
* for the action (excluding 404 responses)
* @throws SwiftInternalStateException the internal state of this client
* is invalid
* @throws FileNotFoundException a 404 response was returned
*/
private <M extends HttpMethod, R> R perform(String reason, URI uri, HttpMethodProcessor<M, R> processor) throws IOException, SwiftBadRequestException, SwiftInternalStateException, SwiftInvalidResponseException, FileNotFoundException {
checkNotNull(uri);
checkNotNull(processor);
final M method = processor.createMethod(uri.toString());
//retry policy
HttpMethodParams methodParams = method.getParams();
methodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retryCount, false));
methodParams.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, connectTimeout);
methodParams.setSoTimeout(socketTimeout);
method.addRequestHeader(HEADER_USER_AGENT, SWIFT_USER_AGENT);
Duration duration = new Duration();
boolean success = false;
try {
int statusCode = 0;
try {
statusCode = exec(method);
} catch (IOException e) {
//rethrow with extra diagnostics and wiki links
throw ExceptionDiags.wrapException(uri.toString(), method.getName(), e);
}
//look at the response and see if it was valid or not.
//Valid is more than a simple 200; even 404 "not found" is considered
//valid -which it is for many methods.
//validate the allowed status code for this operation
int[] allowedStatusCodes = processor.getAllowedStatusCodes();
boolean validResponse = isStatusCodeExpected(statusCode, allowedStatusCodes);
if (!validResponse) {
IOException ioe = buildException(uri, method, statusCode);
throw ioe;
}
R r = processor.extractResult(method);
success = true;
return r;
} catch (IOException e) {
//release the connection -always
method.releaseConnection();
throw e;
} finally {
duration.finished();
durationStats.add(method.getName() + " " + reason, duration, success);
}
}
use of org.apache.commons.httpclient.params.HttpMethodParams in project twitter-2-weibo by rjyo.
the class HttpClient method post.
public Response post(String url, PostParameter[] params, Boolean WithTokenHeader) throws WeiboException {
log("Request:");
log("POST" + url);
PostMethod postMethod = new PostMethod(url);
for (int i = 0; i < params.length; i++) {
postMethod.addParameter(params[i].getName(), params[i].getValue());
}
HttpMethodParams param = postMethod.getParams();
param.setContentCharset("UTF-8");
if (WithTokenHeader) {
return httpRequest(postMethod);
} else {
return httpRequest(postMethod, WithTokenHeader);
}
}
use of org.apache.commons.httpclient.params.HttpMethodParams in project zaproxy by zaproxy.
the class HttpMethodHelper method createRequestMethodNew.
// Not used - all abstract using Generic method but GET cannot be used.
public HttpMethod createRequestMethodNew(HttpRequestHeader header, HttpBody body) throws URIException {
HttpMethod httpMethod = null;
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;
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;
}
Aggregations