use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project zaproxy by zaproxy.
the class HttpSender method runMethod.
private HttpMethod runMethod(HttpMessage msg, boolean isFollowRedirect) throws IOException {
HttpMethod method = null;
// no more retry
modifyUserAgent(msg);
method = helper.createRequestMethod(msg.getRequestHeader(), msg.getRequestBody());
if (!(method instanceof EntityEnclosingMethod)) {
// cant do this for EntityEnclosingMethod methods - it will fail
method.setFollowRedirects(isFollowRedirect);
}
// ZAP: Use custom HttpState if needed
User forceUser = this.getUser(msg);
if (forceUser != null) {
this.executeMethod(method, forceUser.getCorrespondingHttpState());
} else {
this.executeMethod(method, null);
}
HttpMethodHelper.updateHttpRequestHeaderSent(msg.getRequestHeader(), method);
return method;
}
use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project zaproxy by zaproxy.
the class HttpMethodHelper method createRequestMethod.
// This is the currently in use method.
// may be replaced by the New method - however the New method is not yet fully tested so this is stil used.
public HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body) throws URIException {
HttpMethod httpMethod = null;
String method = header.getMethod();
URI uri = header.getURI();
String version = header.getVersion();
if (method == null || method.trim().length() < 3) {
throw new URIException("Invalid HTTP method: " + method);
}
if (method.equalsIgnoreCase(GET)) {
//httpMethod = new GetMethod();
// ZAP: avoid discarding HTTP status code 101 that is used for WebSocket upgrade
httpMethod = new ZapGetMethod();
} else if (method.equalsIgnoreCase(POST)) {
httpMethod = new ZapPostMethod();
} else if (method.equalsIgnoreCase(DELETE)) {
httpMethod = new ZapDeleteMethod();
} else if (method.equalsIgnoreCase(PUT)) {
httpMethod = new ZapPutMethod();
} else if (method.equalsIgnoreCase(HEAD)) {
httpMethod = new ZapHeadMethod();
} else if (method.equalsIgnoreCase(OPTIONS)) {
httpMethod = new ZapOptionsMethod();
} else if (method.equalsIgnoreCase(TRACE)) {
httpMethod = new ZapTraceMethod(uri.toString());
} else {
httpMethod = new GenericMethod(method);
}
try {
httpMethod.setURI(uri);
} catch (Exception e1) {
throw new URIException("Failed to set URI [" + uri + "]: " + e1.getMessage());
}
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: changed to always use CRLF, like the HttpHeader
Pattern pattern = patternCRLF;
String delimiter = header.getLineDelimiter();
// ZAP: Shouldn't happen as the HttpHeader always uses CRLF
if (delimiter.equals(LF)) {
delimiter = LF;
pattern = patternLF;
}
String msg = header.getHeadersAsString();
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 && (httpMethod instanceof EntityEnclosingMethod)) {
EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod;
// post.setRequestEntity(new StringRequestEntity(body.toString()));
post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
}
httpMethod.setFollowRedirects(false);
return httpMethod;
}
use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project openhab1-addons by openhab.
the class Connection method sendCommand.
/**
* Send a command to the Particle REST API (convenience function).
*
* @param device
* the device context, or <code>null</code> if not needed for this command.
* @param funcName
* the function name to call, or variable/field to retrieve if <code>command</code> is
* <code>null</code>.
* @param user
* the user name to use in Basic Authentication if the funcName would require Basic Authentication.
* @param pass
* the password to use in Basic Authentication if the funcName would require Basic Authentication.
* @param command
* the command to send to the API.
* @param proc
* a callback object that receives the status code and response body, or <code>null</code> if not
* needed.
*/
public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command, HttpResponseHandler proc) {
String url = null;
String httpMethod = null;
String content = null;
String contentType = null;
Properties headers = new Properties();
logger.trace("sendCommand: funcName={}", funcName);
switch(funcName) {
case "createToken":
httpMethod = HTTP_POST;
url = TOKEN_URL;
content = command;
contentType = APPLICATION_FORM_URLENCODED;
break;
case "deleteToken":
httpMethod = HTTP_DELETE;
url = String.format(ACCESS_TOKENS_URL, tokens.accessToken);
break;
case "getDevices":
httpMethod = HTTP_GET;
url = String.format(GET_DEVICES_URL, tokens.accessToken);
break;
default:
url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken);
if (command == null) {
// retrieve a variable
httpMethod = HTTP_GET;
} else {
// call a function
httpMethod = HTTP_POST;
content = command;
contentType = APPLICATION_JSON;
}
break;
}
HttpClient client = new HttpClient();
if (!url.contains("access_token=")) {
Credentials credentials = new UsernamePasswordCredentials(user, pass);
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY, credentials);
}
HttpMethod method = createHttpMethod(httpMethod, url);
method.getParams().setSoTimeout(timeout);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
for (String httpHeaderKey : headers.stringPropertyNames()) {
method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey)));
logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey));
}
try {
// add content if a valid method is given ...
if (method instanceof EntityEnclosingMethod && content != null) {
EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null));
logger.trace("content='{}', contentType='{}'", content, contentType);
}
if (logger.isDebugEnabled()) {
try {
logger.debug("About to execute '{}'", method.getURI());
} catch (URIException e) {
logger.debug(e.getMessage());
}
}
int statusCode = client.executeMethod(method);
if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
logger.debug("Method failed: " + method.getStatusLine());
}
String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
if (!responseBody.isEmpty()) {
logger.debug("Body of response: {}", responseBody);
}
if (proc != null) {
proc.handleResponse(statusCode, responseBody);
}
} catch (HttpException he) {
logger.warn("{}", he);
} catch (IOException ioe) {
logger.debug("{}", ioe);
} finally {
method.releaseConnection();
}
}
use of org.apache.commons.httpclient.methods.EntityEnclosingMethod 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;
}
use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project zm-mailbox by Zimbra.
the class ElasticSearchConnector method executeMethod.
public int executeMethod(HttpMethod method) throws IndexStoreException, IOException {
String reqBody = "";
if (ZimbraLog.elasticsearch.isTraceEnabled() && method instanceof EntityEnclosingMethod) {
EntityEnclosingMethod eem = (EntityEnclosingMethod) method;
RequestEntity re = eem.getRequestEntity();
if (re instanceof StringRequestEntity) {
StringRequestEntity sre = (StringRequestEntity) re;
reqBody = Strings.nullToEmpty(sre.getContent());
if (reqBody.length() > 0) {
reqBody = String.format("\nREQUEST BODY=%s", reqBody);
}
}
}
try {
HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
statusCode = client.executeMethod(method);
} catch (ConnectException ce) {
throw new ZimbraElasticSearchDownException(ce);
} catch (NoHttpResponseException nhre) {
// them after retrying a number of times.
throw new ZimbraElasticSearchNoResponseException(nhre);
}
body = method.getResponseBodyAsString();
ZimbraLog.elasticsearch.trace("ElasticSearch request:%s %s - statusCode=%d%s\nRESPONSE BODY=%s", method.getName(), method.getURI(), statusCode, reqBody, body);
return statusCode;
}
Aggregations