Example usage for org.apache.commons.httpclient HttpMethod getParams

List of usage examples for org.apache.commons.httpclient HttpMethod getParams

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getParams.

Prototype

public abstract HttpMethodParams getParams();

Source Link

Usage

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java

@Override
public Object transformMessage(MuleMessage msg, String outputEncoding) throws TransformerException {
    String method = detectHttpMethod(msg);
    try {/*  www  . j  a va  2 s  .c o m*/
        HttpMethod httpMethod;

        if (HttpConstants.METHOD_GET.equals(method)) {
            httpMethod = createGetMethod(msg, outputEncoding);
        } else if (HttpConstants.METHOD_POST.equalsIgnoreCase(method)) {
            httpMethod = createPostMethod(msg, outputEncoding);
        } else if (HttpConstants.METHOD_PUT.equalsIgnoreCase(method)) {
            httpMethod = createPutMethod(msg, outputEncoding);
        } else if (HttpConstants.METHOD_DELETE.equalsIgnoreCase(method)) {
            httpMethod = createDeleteMethod(msg);
        } else if (HttpConstants.METHOD_HEAD.equalsIgnoreCase(method)) {
            httpMethod = createHeadMethod(msg);
        } else if (HttpConstants.METHOD_OPTIONS.equalsIgnoreCase(method)) {
            httpMethod = createOptionsMethod(msg);
        } else if (HttpConstants.METHOD_TRACE.equalsIgnoreCase(method)) {
            httpMethod = createTraceMethod(msg);
        } else if (HttpConstants.METHOD_PATCH.equalsIgnoreCase(method)) {
            httpMethod = createPatchMethod(msg);
        } else {
            throw new TransformerException(HttpMessages.unsupportedMethod(method));
        }

        // Allow the user to set HttpMethodParams as an object on the message
        final HttpMethodParams params = (HttpMethodParams) msg
                .removeProperty(HttpConnector.HTTP_PARAMS_PROPERTY, PropertyScope.OUTBOUND);
        if (params != null) {
            httpMethod.setParams(params);
        } else {
            // TODO we should probably set other properties here
            final String httpVersion = msg.getOutboundProperty(HttpConnector.HTTP_VERSION_PROPERTY,
                    HttpConstants.HTTP11);
            if (HttpConstants.HTTP10.equals(httpVersion)) {
                httpMethod.getParams().setVersion(HttpVersion.HTTP_1_0);
            } else {
                httpMethod.getParams().setVersion(HttpVersion.HTTP_1_1);
            }
        }

        setHeaders(httpMethod, msg);

        return httpMethod;
    } catch (final Exception e) {
        throw new TransformerException(this, e);
    }
}

From source file:org.nuxeo.ecm.platform.web.common.ajax.AjaxProxyServlet.java

protected static String doRequest(String method, String targetURL, HttpServletRequest req) throws IOException {
    HttpClient client = new HttpClient();
    HttpMethod httpMethod;

    if ("GET".equals(method)) {
        httpMethod = new GetMethod(targetURL);
    } else if ("POST".equals(method)) {
        httpMethod = new PostMethod(targetURL);
        ((PostMethod) httpMethod).setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
    } else if ("PUT".equals(method)) {
        httpMethod = new PutMethod(targetURL);
        ((PutMethod) httpMethod).setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
    } else {//from  ww w.  j  a va2s . c  o  m
        throw new IllegalStateException("Unknown HTTP method: " + method);
    }

    Map<String, String[]> params = req.getParameterMap();
    for (String paramName : params.keySet()) {
        httpMethod.getParams().setParameter(paramName, params.get(paramName));
    }

    client.executeMethod(httpMethod);
    String body = httpMethod.getResponseBodyAsString();
    httpMethod.releaseConnection();
    return body;
}

From source file:org.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java

/** {@inheritDoc} */
public HttpResponse fetch(HttpRequest request) {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod;
    String methodType = request.getMethod();
    String requestUri = request.getUri().toString();

    ProxyHelper.fillProxy(httpClient, requestUri);

    // true for non-HEAD requests
    boolean requestCompressedContent = true;

    if ("POST".equals(methodType) || "PUT".equals(methodType)) {
        EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType)) ? new PostMethod(requestUri)
                : new PutMethod(requestUri);

        if (request.getPostBodyLength() > 0) {
            enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody()));
            enclosingMethod.setRequestHeader("Content-Length", String.valueOf(request.getPostBodyLength()));
        }//from  w w  w .j  a  va 2  s .c o  m
        httpMethod = enclosingMethod;
    } else if ("DELETE".equals(methodType)) {
        httpMethod = new DeleteMethod(requestUri);
    } else if ("HEAD".equals(methodType)) {
        httpMethod = new HeadMethod(requestUri);
    } else {
        httpMethod = new GetMethod(requestUri);
    }

    httpMethod.setFollowRedirects(false);
    httpMethod.getParams().setSoTimeout(connectionTimeoutMs);

    if (requestCompressedContent)
        httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");

    for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
    }

    try {

        int statusCode = httpClient.executeMethod(httpMethod);

        // Handle redirects manually
        if (request.getFollowRedirects() && ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) {

            Header header = httpMethod.getResponseHeader("location");
            if (header != null) {
                String redirectUri = header.getValue();

                if ((redirectUri == null) || (redirectUri.equals(""))) {
                    redirectUri = "/";
                }
                httpMethod.releaseConnection();
                httpMethod = new GetMethod(redirectUri);

                statusCode = httpClient.executeMethod(httpMethod);
            }
        }

        return makeResponse(httpMethod, statusCode);

    } catch (IOException e) {
        if (e instanceof java.net.SocketTimeoutException || e instanceof java.net.SocketException) {
            return HttpResponse.timeout();
        }

        return HttpResponse.error();

    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:org.openhab.binding.frontiersiliconradio.internal.FrontierSiliconRadioConnection.java

/**
 * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for
 * future requests./*from  w  w w.j av a 2s. c o  m*/
 * 
 * @return <code>true</code> if login was successful; <code>false</code> otherwise.
 */
public boolean doLogin() {
    isLoggedIn = false; // reset login flag

    if (httpClient == null) {
        httpClient = new HttpClient();
    }

    final String url = "http://" + hostname + ":" + port + "/fsapi/CREATE_SESSION?pin=" + pin;

    logger.trace("opening URL:" + url);

    final HttpMethod method = new GetMethod(url);
    method.getParams().setSoTimeout(SOCKET_TIMEOUT);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        final int statusCode = httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }

        final String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.trace("login response: " + responseBody);
        }

        try {
            final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
            if (result.isStatusOk()) {
                logger.trace("login successful");
                sessionId = result.getSessionId();
                isLoggedIn = true;
                return true; // login successful :-)
            }
        } catch (Exception e) {
            logger.error("Parsing response failed");
        }

    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }
    return false; // login not successful
}

From source file:org.openhab.binding.frontiersiliconradio.internal.FrontierSiliconRadioConnection.java

/**
 * Performs a request to the radio with addition parameters.
 * //from   w  ww .  ja va  2  s  .  c  o  m
 * Typically used for changing parameters.
 * 
 * @param REST
 *            API requestString, e.g. "SET/netRemote.sys.power"
 * @param params
 *            , e.g. "value=1"
 * @return request result
 */
public FrontierSiliconRadioApiResult doRequest(String requestString, String params) {

    // 3 retries upon failure
    for (int i = 0; i < 3; i++) {
        if (!isLoggedIn && !doLogin()) {
            continue; // not logged in and login was not successful - try again!
        }

        final String url = "http://" + hostname + ":" + port + "/fsapi/" + requestString + "?pin=" + pin
                + "&sid=" + sessionId + (params == null || params.trim().length() == 0 ? "" : "&" + params);

        logger.trace("calling url: '" + url + "'");

        final HttpMethod method = new GetMethod(url);
        method.getParams().setSoTimeout(SOCKET_TIMEOUT);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        try {

            final int statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                logger.warn("Method failed: " + method.getStatusLine());
                isLoggedIn = false;
                method.releaseConnection();
                continue;
            }

            final String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
            if (!responseBody.isEmpty()) {
                logger.trace("got result: " + responseBody);
            } else {
                logger.debug("got empty result");
                isLoggedIn = false;
                method.releaseConnection();
                continue;
            }

            final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
            if (result.isStatusOk())
                return result;

            isLoggedIn = false;
            method.releaseConnection();
            continue; // try again
        } catch (HttpException he) {
            logger.error("Fatal protocol violation: {}", he.toString());
            isLoggedIn = false;
        } catch (IOException ioe) {
            logger.error("Fatal transport error: {}", ioe.toString());
        } finally {
            method.releaseConnection();
        }
    }
    isLoggedIn = false; // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?)
    return null;
}

From source file:org.openhab.binding.garadget.internal.Connection.java

/**
 * Send a command to the Particle REST API (convenience function).
 *
 * @param device/*from   w  w w  .  j av  a2 s .  c  o m*/
 *            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();

    // Only perform basic authentication when we aren't using OAuth

    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();
    }
}

From source file:org.openhab.binding.nest.internal.messages.AbstractRequest.java

/**
 * 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.
 * /* w w  w  .  j a v  a2  s  .  c o  m*/
 * @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(HTTP_REQUEST_TIMEOUT);
    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;
}

From source file:org.openhab.io.net.http.HttpUtil.java

/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>
 * /*  w  w w  .  j  av  a 2  s  .  c o m*/
 * @param httpMethod the HTTP method to use
 * @param url the url to execute (in milliseconds)
 * @param httpHeaders optional HTTP headers which has to be set on request
 * @param content the content to be send to the given <code>url</code> or 
 * <code>null</code> if no content should be send.
 * @param contentType the content type of the given <code>content</code>
 * @param timeout the socket timeout to wait for data
 * @param proxyHost the hostname of the proxy
 * @param proxyPort the port of the proxy
 * @param proxyUser the username to authenticate with the proxy
 * @param proxyPassword the password to authenticate with the proxy
 * @param nonProxyHosts the hosts that won't be routed through the proxy
 * @return the response body or <code>NULL</code> when the request went wrong
 */
public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser,
        String proxyPassword, String nonProxyHosts) {

    HttpClient client = new HttpClient();

    // only configure a proxy if a host is provided
    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (StringUtils.isNotBlank(proxyUser)) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
    }

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (httpHeaders != null) {
        for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
            method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
        }
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && content != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    Credentials credentials = extractCredentials(url);
    if (credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.debug("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.debug(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;
        }

        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.debug("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.debug("Deflated InputStream from {}", url);
                }
            }
        }

        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.debug(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;
}

From source file:org.parosproxy.paros.network.HttpMethodHelper.java

public HttpMethod createRequestMethodNew(HttpRequestHeader header, HttpBody body) throws URIException {
    HttpMethod httpMethod = null;

    String method = header.getMethod();
    URI uri = header.getURI();//www  .  j  a v  a  2s.  c o  m
    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;
    //String host = 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;

}

From source file:org.parosproxy.paros.network.HttpMethodHelper.java

public HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body) throws URIException {
    HttpMethod httpMethod = null;

    String method = header.getMethod();
    URI uri = header.getURI();/*  ww w.j  a  v a2s .  com*/
    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) {
        logger.error(e1.getMessage(), e1);
    }

    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;

}