Search in sources :

Example 6 with EntityEnclosingMethod

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;
}
Also used : User(org.zaproxy.zap.users.User) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 7 with EntityEnclosingMethod

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;
}
Also used : ZapPutMethod(org.zaproxy.zap.network.ZapPutMethod) Pattern(java.util.regex.Pattern) ZapGetMethod(org.zaproxy.zap.ZapGetMethod) ZapTraceMethod(org.zaproxy.zap.network.ZapTraceMethod) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) ZapOptionsMethod(org.zaproxy.zap.network.ZapOptionsMethod) ZapHeadMethod(org.zaproxy.zap.network.ZapHeadMethod) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) URI(org.apache.commons.httpclient.URI) URIException(org.apache.commons.httpclient.URIException) URIException(org.apache.commons.httpclient.URIException) ZapPostMethod(org.zaproxy.zap.network.ZapPostMethod) ZapDeleteMethod(org.zaproxy.zap.network.ZapDeleteMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 8 with EntityEnclosingMethod

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();
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) Properties(java.util.Properties) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 9 with EntityEnclosingMethod

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;
}
Also used : Pattern(java.util.regex.Pattern) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) URI(org.apache.commons.httpclient.URI) HttpMethod(org.apache.commons.httpclient.HttpMethod) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 10 with EntityEnclosingMethod

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;
}
Also used : NoHttpResponseException(org.apache.commons.httpclient.NoHttpResponseException) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) HttpClient(org.apache.commons.httpclient.HttpClient) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) ConnectException(java.net.ConnectException)

Aggregations

EntityEnclosingMethod (org.apache.commons.httpclient.methods.EntityEnclosingMethod)10 HttpMethod (org.apache.commons.httpclient.HttpMethod)6 IOException (java.io.IOException)4 HttpException (org.apache.commons.httpclient.HttpException)4 URIException (org.apache.commons.httpclient.URIException)4 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)4 StringRequestEntity (org.apache.commons.httpclient.methods.StringRequestEntity)4 HttpClient (org.apache.commons.httpclient.HttpClient)3 RequestEntity (org.apache.commons.httpclient.methods.RequestEntity)3 HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)3 Pattern (java.util.regex.Pattern)2 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)2 Header (org.apache.commons.httpclient.Header)2 URI (org.apache.commons.httpclient.URI)2 InputStreamRequestEntity (org.apache.commons.httpclient.methods.InputStreamRequestEntity)2 SpanEventRecorder (com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder)1 BufferedInputStream (java.io.BufferedInputStream)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 ConnectException (java.net.ConnectException)1