Example usage for org.apache.commons.httpclient HttpMethodBase addRequestHeader

List of usage examples for org.apache.commons.httpclient HttpMethodBase addRequestHeader

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethodBase addRequestHeader.

Prototype

@Override
public void addRequestHeader(Header header) 

Source Link

Document

Adds the specified request header, NOT overwriting any previous value.

Usage

From source file:com.arjuna.qa.junit.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);

    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {//from w w  w.j  a  v a 2s  . c  o  m
        System.err.println("Connecting to: " + url);
        String userInfo = url.getUserInfo();

        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        System.err.println("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        System.err.println("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        System.err.println(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:org.alfresco.repo.remoteconnector.RemoteConnectorServiceImpl.java

/**
 * Executes the specified request, and return the response
 *///from w w w  . j a  v a 2 s . com
public RemoteConnectorResponse executeRequest(RemoteConnectorRequest request) throws IOException,
        AuthenticationException, RemoteConnectorClientException, RemoteConnectorServerException {
    RemoteConnectorRequestImpl reqImpl = (RemoteConnectorRequestImpl) request;
    HttpMethodBase httpRequest = reqImpl.getMethodInstance();

    // Attach the headers to the request
    for (Header hdr : request.getRequestHeaders()) {
        httpRequest.addRequestHeader(hdr);
    }

    // Attach the body, if possible
    if (httpRequest instanceof EntityEnclosingMethod) {
        if (request.getRequestBody() != null) {
            ((EntityEnclosingMethod) httpRequest).setRequestEntity(reqImpl.getRequestBody());
        }
    }

    // Grab our thread local HttpClient instance
    // Remember - we must then clean it up!
    HttpClient httpClient = HttpClientHelper.getHttpClient();

    // The url should already be vetted by the RemoteConnectorRequest
    URL url = new URL(request.getURL());

    // Use the appropriate Proxy Host if required
    if (httpProxyHost != null && url.getProtocol().equals("http") && requiresProxy(url.getHost())) {
        httpClient.getHostConfiguration().setProxyHost(httpProxyHost);
        if (logger.isDebugEnabled())
            logger.debug(" - using HTTP proxy host for: " + url);
        if (httpProxyCredentials != null) {
            httpClient.getState().setProxyCredentials(httpAuthScope, httpProxyCredentials);
            if (logger.isDebugEnabled())
                logger.debug(" - using HTTP proxy credentials for proxy: " + httpProxyHost.getHostName());
        }
    } else if (httpsProxyHost != null && url.getProtocol().equals("https") && requiresProxy(url.getHost())) {
        httpClient.getHostConfiguration().setProxyHost(httpsProxyHost);
        if (logger.isDebugEnabled())
            logger.debug(" - using HTTPS proxy host for: " + url);
        if (httpsProxyCredentials != null) {
            httpClient.getState().setProxyCredentials(httpsAuthScope, httpsProxyCredentials);
            if (logger.isDebugEnabled())
                logger.debug(" - using HTTPS proxy credentials for proxy: " + httpsProxyHost.getHostName());
        }
    } else {
        //host should not be proxied remove any configured proxies
        httpClient.getHostConfiguration().setProxyHost(null);
        httpClient.getState().clearProxyCredentials();
    }

    // Log what we're doing
    if (logger.isDebugEnabled()) {
        logger.debug("Performing " + request.getMethod() + " request to " + request.getURL());
        for (Header hdr : request.getRequestHeaders()) {
            logger.debug("Header: " + hdr);
        }
        Object requestBody = null;
        if (request != null) {
            requestBody = request.getRequestBody();
        }
        if (requestBody != null && requestBody instanceof StringRequestEntity) {
            StringRequestEntity re = (StringRequestEntity) request.getRequestBody();
            logger.debug("Payload (string): " + re.getContent());
        } else if (requestBody != null && requestBody instanceof ByteArrayRequestEntity) {
            ByteArrayRequestEntity re = (ByteArrayRequestEntity) request.getRequestBody();
            logger.debug("Payload (byte array): " + re.getContent().toString());
        } else {
            logger.debug("Payload is not of a readable type.");
        }
    }

    // Perform the request, and wrap the response
    int status = -1;
    String statusText = null;
    RemoteConnectorResponse response = null;
    try {
        status = httpClient.executeMethod(httpRequest);
        statusText = httpRequest.getStatusText();

        Header[] responseHdrs = httpRequest.getResponseHeaders();
        Header responseContentTypeH = httpRequest
                .getResponseHeader(RemoteConnectorRequestImpl.HEADER_CONTENT_TYPE);
        String responseCharSet = httpRequest.getResponseCharSet();
        String responseContentType = (responseContentTypeH != null ? responseContentTypeH.getValue() : null);

        if (logger.isDebugEnabled()) {
            logger.debug(
                    "response url=" + request.getURL() + ", length =" + httpRequest.getResponseContentLength()
                            + ", responceContentType " + responseContentType + ", statusText =" + statusText);
        }

        // Decide on how best to handle the response, based on the size
        // Ideally, we want to close the HttpClient resources immediately, but
        //  that isn't possible for very large responses
        // If we can close immediately, it makes cleanup simpler and fool-proof
        if (httpRequest.getResponseContentLength() > MAX_BUFFER_RESPONSE_SIZE
                || httpRequest.getResponseContentLength() == -1) {
            if (logger.isTraceEnabled()) {
                logger.trace("large response (or don't know length) url=" + request.getURL());
            }

            // Need to wrap the InputStream in something that'll close
            InputStream wrappedStream = new HttpClientReleasingInputStream(httpRequest);
            httpRequest = null;

            // Now build the response
            response = new RemoteConnectorResponseImpl(request, responseContentType, responseCharSet, status,
                    responseHdrs, wrappedStream);
        } else {
            if (logger.isTraceEnabled()) {
                logger.debug("small response for url=" + request.getURL());
            }
            // Fairly small response, just keep the bytes and make life simple
            response = new RemoteConnectorResponseImpl(request, responseContentType, responseCharSet, status,
                    responseHdrs, httpRequest.getResponseBody());

            // Now we have the bytes, we can close the HttpClient resources
            httpRequest.releaseConnection();
            httpRequest = null;
        }
    } finally {
        // Make sure, problems or not, we always tidy up (if not large stream based)
        // This is important because we use a thread local HttpClient instance
        if (httpRequest != null) {
            httpRequest.releaseConnection();
            httpRequest = null;
        }
    }

    // Log the response
    if (logger.isDebugEnabled())
        logger.debug("Response was " + status + " " + statusText);

    // Decide if we should throw an exception
    if (status >= 300) {
        // Tidy if needed
        if (httpRequest != null)
            httpRequest.releaseConnection();

        // Specific exceptions
        if (status == Status.STATUS_FORBIDDEN || status == Status.STATUS_UNAUTHORIZED) {
            // TODO Forbidden may need to be handled differently.
            // TODO Need to get error message into the AuthenticationException
            throw new AuthenticationException(statusText);
        }

        // Server side exceptions
        if (status >= 500 && status <= 599) {
            logger.error("executeRequest: remote connector server exception: [" + status + "] " + statusText);
            throw new RemoteConnectorServerException(status, statusText);
        }
        if (status == Status.STATUS_PRECONDITION_FAILED) {
            logger.error("executeRequest: remote connector client exception: [" + status + "] " + statusText);
            throw new RemoteConnectorClientException(status, statusText, response);
        } else {
            // Client request exceptions
            if (httpRequest != null) {
                // Response wasn't too big and is available, supply it
                logger.error(
                        "executeRequest: remote connector client exception: [" + status + "] " + statusText);
                throw new RemoteConnectorClientException(status, statusText, response);
            } else {
                // Response was too large, report without it
                logger.error(
                        "executeRequest: remote connector client exception: [" + status + "] " + statusText);
                throw new RemoteConnectorClientException(status, statusText, null);
            }
        }
    }

    // If we get here, then the request/response was all fine
    // So, return our created response
    return response;
}

From source file:org.apache.hadoop.fs.swift.http.SwiftRestClient.java

/**
 * Add the headers to the method, and the auth token (which must be set
 * @param method method to update/*  w ww  .ja v  a 2s.  co m*/
 * @param requestHeaders the list of headers
 * @throws SwiftInternalStateException not yet authenticated
 */
private void setHeaders(HttpMethodBase method, Header[] requestHeaders) throws SwiftInternalStateException {
    for (Header header : requestHeaders) {
        method.addRequestHeader(header);
    }
    setAuthToken(method, getToken());
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.http.HttpResponse.java

/**
 * Sets the http parameters.//w w w  .  j a v  a 2 s.  c om
 * 
 * @param http
 *          the http
 * @param httpMethod
 *          the http method
 */
private void setHttpParameters(HttpBase http, HttpMethodBase httpMethod) {
    httpMethod.setFollowRedirects(false);
    httpMethod.setRequestHeader("User-Agent", http.getUserAgent());
    httpMethod.setRequestHeader("Referer", http.getReferer());

    httpMethod.setDoAuthentication(true);

    for (Header header : http.getHeaders()) {
        httpMethod.addRequestHeader(header);
    }

    final HttpMethodParams params = httpMethod.getParams();
    if (http.getUseHttp11()) {
        params.setVersion(HttpVersion.HTTP_1_1);
    } else {
        params.setVersion(HttpVersion.HTTP_1_0);
    }
    params.makeLenient();
    params.setContentCharset("UTF-8");

    if (http.isCookiesEnabled()) {
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    } else {
        params.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    }
    params.setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true);
    // the default is to retry 3 times; if
    // the request body was sent the method is not retried, so there is
    // little danger in retrying
    // retries are handled on the higher level
    params.setParameter(HttpMethodParams.RETRY_HANDLER, null);
}

From source file:org.jaggeryjs2.xhr.XMLHttpRequest.java

private void sendRequest(Object obj) throws Exception {
    final HttpMethodBase method;
    if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod(this.url);
    } else if ("HEAD".equalsIgnoreCase(methodName)) {
        method = new HeadMethod(this.url);
    } else if ("POST".equalsIgnoreCase(methodName)) {
        PostMethod post = new PostMethod(this.url);
        if (obj instanceof FormData) {
            FormData fd = ((FormData) obj);
            List<Part> parts = new ArrayList<Part>();
            for (Map.Entry<String, String> entry : fd) {
                parts.add(new StringPart(entry.getKey(), entry.getValue()));
            }//  w  ww .  j av a2s.co  m
            post.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));
        } else {
            String content = getRequestContent(obj);
            if (content != null) {
                post.setRequestEntity(
                        new InputStreamRequestEntity(new ByteArrayInputStream(content.getBytes())));
            }
        }
        method = post;
    } else if ("PUT".equalsIgnoreCase(methodName)) {
        PutMethod put = new PutMethod(this.url);
        String content = getRequestContent(obj);
        if (content != null) {
            put.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(content.getBytes())));
        }
        method = put;
    } else if ("DELETE".equalsIgnoreCase(methodName)) {
        method = new DeleteMethod(this.url);
    } else if ("TRACE".equalsIgnoreCase(methodName)) {
        method = new TraceMethod(this.url);
    } else if ("OPTIONS".equalsIgnoreCase(methodName)) {
        method = new OptionsMethod(this.url);
    } else {
        throw new Exception("Unknown HTTP method : " + methodName);
    }
    for (Header header : requestHeaders) {
        method.addRequestHeader(header);
    }
    if (username != null) {
        httpClient.getState().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(username, password));
    }
    this.method = method;
    final XMLHttpRequest xhr = this;
    if (async) {
        updateReadyState(xhr, LOADING);
        final ExecutorService es = Executors.newSingleThreadExecutor();
        es.submit(new Callable() {
            public Object call() throws Exception {
                try {
                    executeRequest(xhr);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                } finally {
                    es.shutdown();
                }
                return null;
            }
        });
    } else {
        executeRequest(xhr);
    }
}

From source file:org.jboss.ejb3.test.clusteredservice.unit.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);

    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {//from  w w w  . j a  v a 2 s. c o m
        log.debug("Connecting to: " + url);
        String userInfo = url.getUserInfo();

        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        log.debug("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        log.debug("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        log.debug(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:org.jboss.test.util.web.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);
    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {// w w  w .  ja v a 2 s  . com
        log.debug("Connecting to: " + url);
        String userInfo = url.getUserInfo();
        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        log.debug("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        log.debug("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        log.debug(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:org.tinygroup.httpvisit.impl.HttpVisitorImpl.java

private void addHeader(HttpMethodBase method, Map<String, String> header) {
    if (header != null) {
        for (String key : header.keySet()) {
            Header h = new Header(key, header.get(key));
            method.addRequestHeader(h);
        }/*from   ww  w  .j  a  v  a2 s  .c o  m*/
    }
}