Example usage for org.apache.http.client.methods HttpHead HttpHead

List of usage examples for org.apache.http.client.methods HttpHead HttpHead

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpHead HttpHead.

Prototype

public HttpHead(final String uri) 

Source Link

Usage

From source file:org.commonjava.couch.db.CouchManager.java

public boolean exists(final String path) throws CouchDBException {
    boolean exists = false;

    String url;/*from w w  w.  j a va  2s  .  c  o m*/
    try {
        url = buildUrl(config.getDatabaseUrl(), path);
    } catch (final MalformedURLException e) {
        throw new CouchDBException("Invalid path: %s. Reason: %s", e, path, e.getMessage());
    }

    final HttpHead request = new HttpHead(url);
    try {
        final HttpResponse response = client.executeHttpWithResponse(request, "Failed to ping database URL");

        final StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == SC_OK) {
            exists = true;
        } else if (statusLine.getStatusCode() != SC_NOT_FOUND) {
            final HttpEntity entity = response.getEntity();
            CouchError error;

            try {
                error = serializer.toError(entity);
            } catch (final IOException e) {
                throw new CouchDBException(
                        "Failed to ping database URL: %s.\nReason: %s\nError: Cannot read error status: %s", e,
                        url, statusLine, e.getMessage());
            }

            throw new CouchDBException("Failed to ping database URL: %s.\nReason: %s\nError: %s", url,
                    statusLine, error);
        }
    } finally {
        client.cleanup(request);
    }

    return exists;
}

From source file:org.apache.solr.servlet.HttpSolrCall.java

private void remoteQuery(String coreUrl, HttpServletResponse resp) throws IOException {
    HttpRequestBase method = null;/* w ww  .ja  va 2s.  c om*/
    HttpEntity httpEntity = null;
    try {
        String urlstr = coreUrl + queryParams.toQueryString();

        boolean isPostOrPutRequest = "POST".equals(req.getMethod()) || "PUT".equals(req.getMethod());
        if ("GET".equals(req.getMethod())) {
            method = new HttpGet(urlstr);
        } else if ("HEAD".equals(req.getMethod())) {
            method = new HttpHead(urlstr);
        } else if (isPostOrPutRequest) {
            HttpEntityEnclosingRequestBase entityRequest = "POST".equals(req.getMethod()) ? new HttpPost(urlstr)
                    : new HttpPut(urlstr);
            InputStream in = new CloseShieldInputStream(req.getInputStream()); // Prevent close of container streams
            HttpEntity entity = new InputStreamEntity(in, req.getContentLength());
            entityRequest.setEntity(entity);
            method = entityRequest;
        } else if ("DELETE".equals(req.getMethod())) {
            method = new HttpDelete(urlstr);
        } else {
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                    "Unexpected method type: " + req.getMethod());
        }

        for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements();) {
            String headerName = e.nextElement();
            if (!"host".equalsIgnoreCase(headerName) && !"authorization".equalsIgnoreCase(headerName)
                    && !"accept".equalsIgnoreCase(headerName)) {
                method.addHeader(headerName, req.getHeader(headerName));
            }
        }
        // These headers not supported for HttpEntityEnclosingRequests
        if (method instanceof HttpEntityEnclosingRequest) {
            method.removeHeaders(TRANSFER_ENCODING_HEADER);
            method.removeHeaders(CONTENT_LENGTH_HEADER);
        }

        final HttpResponse response = solrDispatchFilter.httpClient.execute(method,
                HttpClientUtil.createNewHttpClientRequestContext());
        int httpStatus = response.getStatusLine().getStatusCode();
        httpEntity = response.getEntity();

        resp.setStatus(httpStatus);
        for (HeaderIterator responseHeaders = response.headerIterator(); responseHeaders.hasNext();) {
            Header header = responseHeaders.nextHeader();

            // We pull out these two headers below because they can cause chunked
            // encoding issues with Tomcat
            if (header != null && !header.getName().equalsIgnoreCase(TRANSFER_ENCODING_HEADER)
                    && !header.getName().equalsIgnoreCase(CONNECTION_HEADER)) {
                resp.addHeader(header.getName(), header.getValue());
            }
        }

        if (httpEntity != null) {
            if (httpEntity.getContentEncoding() != null)
                resp.setCharacterEncoding(httpEntity.getContentEncoding().getValue());
            if (httpEntity.getContentType() != null)
                resp.setContentType(httpEntity.getContentType().getValue());

            InputStream is = httpEntity.getContent();
            OutputStream os = resp.getOutputStream();

            IOUtils.copyLarge(is, os);
        }

    } catch (IOException e) {
        sendError(new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                "Error trying to proxy request for url: " + coreUrl, e));
    } finally {
        Utils.consumeFully(httpEntity);
    }

}

From source file:com.flyn.net.asynchttp.AsyncHttpClient.java

/**
 * Perform a HTTP HEAD request and track the Android Context which initiated
 * the request with customized headers//from   ww  w  .j  a va2s  .  co m
 *
 * @param context         Context to execute request against
 * @param url             the URL to send the request to.
 * @param headers         set headers only for this request
 * @param params          additional HEAD parameters to send with the request.
 * @param responseHandler the response handler instance that should handle the response.
 * @return RequestHandle of future request process
 */
public RequestHandle head(Context context, String url, Header[] headers, RequestParams params,
        ResponseHandlerInterface responseHandler) {
    HttpUriRequest request = new HttpHead(getUrlWithQueryString(isUrlEncodingEnabled, url, params));
    if (headers != null) {
        request.setHeaders(headers);
    }
    return sendRequest(httpClient, httpContext, request, null, responseHandler, context);
}

From source file:org.apache.solr.util.SolrCLI.java

/**
 * Tries a simple HEAD request and throws SolrException in case of Authorization error
 * @param url the url to do a HEAD request to
 * @param httpClient the http client to use (make sure it has authentication optinos set)
 * @return the HTTP response code/*w ww  . j a va 2  s  .  c o m*/
 * @throws SolrException if auth/autz problems
 * @throws IOException if connection failure
 */
private static int attemptHttpHead(String url, HttpClient httpClient) throws SolrException, IOException {
    HttpResponse response = httpClient.execute(new HttpHead(url),
            HttpClientUtil.createNewHttpClientRequestContext());
    int code = response.getStatusLine().getStatusCode();
    if (code == UNAUTHORIZED.code || code == FORBIDDEN.code) {
        throw new SolrException(SolrException.ErrorCode.getErrorCode(code), "Solr requires authentication for "
                + url + ". Please supply valid credentials. HTTP code=" + code);
    }
    return code;
}

From source file:com.enjoy.nerd.http.AsyncHttpClient.java

/**
 * Perform a HTTP HEAD request and track the Android Context which initiated the request with
 * customized headers//from  w  w w.j  av a 2  s  . c  o  m
 *
 * @param context         Context to execute request against
 * @param url             the URL to send the request to.
 * @param headers         set headers only for this request
 * @param params          additional HEAD parameters to send with the request.
 * @param responseHandler the response handler instance that should handle the response.
 * @return RequestHandle of future request process
 */
public RequestHandle head(Context context, String url, Header[] headers, RequestParams params,
        ResponseHandlerInterface responseHandler) {
    HttpUriRequest request = new HttpHead(getUrlWithQueryString(isUrlEncodingEnabled, url, params));
    if (headers != null)
        request.setHeaders(headers);
    SyncBasicHttpContext httpContext = new SyncBasicHttpContext(mBasicHttpContext);
    return sendRequest(httpClient, httpContext, request, null, responseHandler, context);
}

From source file:org.dasein.cloud.azure.AzureMethod.java

protected HttpRequestBase getMethod(String httpMethod, String url) {
    HttpRequestBase method = null;/*from  w  ww .ja v  a  2 s . c o  m*/
    if (httpMethod.equals("GET")) {
        method = new HttpGet(url);
    } else if (httpMethod.equals("POST")) {
        method = new HttpPost(url);
    } else if (httpMethod.equals("PUT")) {
        method = new HttpPut(url);
    } else if (httpMethod.equals("DELETE")) {
        method = new HttpDelete(url);
    } else if (httpMethod.equals("HEAD")) {
        method = new HttpHead(url);
    } else if (httpMethod.equals("OPTIONS")) {
        method = new HttpOptions(url);
    } else if (httpMethod.equals("HEAD")) {
        method = new HttpTrace(url);
    } else {
        method = new HttpGet(url);
    }
    return method;
}

From source file:com.googlecode.sardine.impl.SardineImpl.java

/**
 * (non-Javadoc)//w  w  w . java2 s.  co  m
 * 
 * @see com.googlecode.sardine.Sardine#exists(java.lang.String)
 */
public boolean exists(String url) throws IOException {
    HttpHead head = new HttpHead(url);
    return this.execute(head, new ExistsResponseHandler());
}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java

private boolean resourceExists(int wait, String resourceName)
        throws TransferFailedException, AuthorizationException {
    String repositoryUrl = getRepository().getUrl();
    String url = repositoryUrl + (repositoryUrl.endsWith("/") ? "" : "/") + resourceName;
    HttpHead headMethod = new HttpHead(url);
    try {//www  . j av  a 2 s .  c  o m
        CloseableHttpResponse response = execute(headMethod);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            String reasonPhrase = ", ReasonPhrase: " + response.getStatusLine().getReasonPhrase() + ".";
            boolean result;
            switch (statusCode) {
            case HttpStatus.SC_OK:
                result = true;
                break;
            case HttpStatus.SC_NOT_MODIFIED:
                result = true;
                break;
            case HttpStatus.SC_FORBIDDEN:
                throw new AuthorizationException("Access denied to: " + url + reasonPhrase);

            case HttpStatus.SC_UNAUTHORIZED:
                throw new AuthorizationException("Not authorized " + reasonPhrase);

            case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
                throw new AuthorizationException("Not authorized by proxy " + reasonPhrase);

            case HttpStatus.SC_NOT_FOUND:
                result = false;
                break;

            case SC_TOO_MANY_REQUESTS:
                return resourceExists(backoff(wait, resourceName), resourceName);

            //add more entries here
            default:
                throw new TransferFailedException(
                        "Failed to transfer file: " + url + ". Return code is: " + statusCode + reasonPhrase);
            }

            EntityUtils.consume(response.getEntity());
            return result;
        } finally {
            response.close();
        }
    } catch (IOException e) {
        throw new TransferFailedException(e.getMessage(), e);
    } catch (HttpException e) {
        throw new TransferFailedException(e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new TransferFailedException(e.getMessage(), e);
    }

}

From source file:org.elasticsearch.client.RestClient.java

private static HttpRequestBase createHttpRequest(String method, URI uri, HttpEntity entity) {
    switch (method.toUpperCase(Locale.ROOT)) {
    case HttpDeleteWithEntity.METHOD_NAME:
        return addRequestBody(new HttpDeleteWithEntity(uri), entity);
    case HttpGetWithEntity.METHOD_NAME:
        return addRequestBody(new HttpGetWithEntity(uri), entity);
    case HttpHead.METHOD_NAME:
        return addRequestBody(new HttpHead(uri), entity);
    case HttpOptions.METHOD_NAME:
        return addRequestBody(new HttpOptions(uri), entity);
    case HttpPatch.METHOD_NAME:
        return addRequestBody(new HttpPatch(uri), entity);
    case HttpPost.METHOD_NAME:
        HttpPost httpPost = new HttpPost(uri);
        addRequestBody(httpPost, entity);
        return httpPost;
    case HttpPut.METHOD_NAME:
        return addRequestBody(new HttpPut(uri), entity);
    case HttpTrace.METHOD_NAME:
        return addRequestBody(new HttpTrace(uri), entity);
    default://from   www  .  j  a v  a 2 s.  c  om
        throw new UnsupportedOperationException("http method not supported: " + method);
    }
}

From source file:lucee.runtime.tag.Http4.java

private void _doEndTag(Struct cfhttp) throws PageException, IOException {
    BasicHttpParams params = new BasicHttpParams();
    DefaultHttpClient client = HTTPEngine4Impl.createClient(params, redirect ? HTTPEngine.MAX_REDIRECT : 0);

    ConfigWeb cw = pageContext.getConfig();
    HttpRequestBase req = null;//www .ja v a 2 s  . c om
    HttpContext httpContext = null;
    //HttpRequestBase req = init(pageContext.getConfig(),this,client,params,url,port);
    {
        if (StringUtil.isEmpty(charset, true))
            charset = ((PageContextImpl) pageContext).getWebCharset().name();
        else
            charset = charset.trim();

        // check if has fileUploads   
        boolean doUploadFile = false;
        for (int i = 0; i < this.params.size(); i++) {
            if ((this.params.get(i)).getType().equalsIgnoreCase("file")) {
                doUploadFile = true;
                break;
            }
        }

        // parse url (also query string)
        int len = this.params.size();
        StringBuilder sbQS = new StringBuilder();
        for (int i = 0; i < len; i++) {
            HttpParamBean param = this.params.get(i);
            String type = param.getType();
            // URL
            if (type.equals("url")) {
                if (sbQS.length() > 0)
                    sbQS.append('&');
                sbQS.append(param.getEncoded() ? HttpImpl.urlenc(param.getName(), charset) : param.getName());
                sbQS.append('=');
                sbQS.append(param.getEncoded() ? HttpImpl.urlenc(param.getValueAsString(), charset)
                        : param.getValueAsString());
            }
        }
        String host = null;
        HttpHost httpHost;
        try {
            URL _url = HTTPUtil.toURL(url, port, encoded);
            httpHost = new HttpHost(_url.getHost(), _url.getPort());
            host = _url.getHost();
            url = _url.toExternalForm();
            if (sbQS.length() > 0) {
                // no existing QS
                if (StringUtil.isEmpty(_url.getQuery())) {
                    url += "?" + sbQS;
                } else {
                    url += "&" + sbQS;
                }
            }
        } catch (MalformedURLException mue) {
            throw Caster.toPageException(mue);
        }

        // select best matching method (get,post, post multpart (file))

        boolean isBinary = false;
        boolean doMultiPart = doUploadFile || this.multiPart;
        HttpPost post = null;
        HttpEntityEnclosingRequest eem = null;

        if (this.method == METHOD_GET) {
            req = new HttpGet(url);
        } else if (this.method == METHOD_HEAD) {
            req = new HttpHead(url);
        } else if (this.method == METHOD_DELETE) {
            isBinary = true;
            req = new HttpDelete(url);
        } else if (this.method == METHOD_PUT) {
            isBinary = true;
            HttpPut put = new HttpPut(url);
            req = put;
            eem = put;

        } else if (this.method == METHOD_TRACE) {
            isBinary = true;
            req = new HttpTrace(url);
        } else if (this.method == METHOD_OPTIONS) {
            isBinary = true;
            req = new HttpOptions(url);
        } else if (this.method == METHOD_PATCH) {
            isBinary = true;
            eem = HTTPPatchFactory.getHTTPPatch(url);
            req = (HttpRequestBase) eem;
        } else {
            isBinary = true;
            post = new HttpPost(url);
            req = post;
            eem = post;
        }

        boolean hasForm = false;
        boolean hasBody = false;
        boolean hasContentType = false;
        // Set http params
        ArrayList<FormBodyPart> parts = new ArrayList<FormBodyPart>();

        StringBuilder acceptEncoding = new StringBuilder();
        java.util.List<NameValuePair> postParam = post != null ? new ArrayList<NameValuePair>() : null;

        for (int i = 0; i < len; i++) {
            HttpParamBean param = this.params.get(i);
            String type = param.getType();

            // URL
            if (type.equals("url")) {
                //listQS.add(new BasicNameValuePair(translateEncoding(param.getName(), http.charset),translateEncoding(param.getValueAsString(), http.charset)));
            }
            // Form
            else if (type.equals("formfield") || type.equals("form")) {
                hasForm = true;
                if (this.method == METHOD_GET)
                    throw new ApplicationException(
                            "httpparam with type formfield can only be used when the method attribute of the parent http tag is set to post");
                if (post != null) {
                    if (doMultiPart) {
                        parts.add(new FormBodyPart(param.getName(),
                                new StringBody(param.getValueAsString(), CharsetUtil.toCharset(charset))));
                    } else {
                        postParam.add(new BasicNameValuePair(param.getName(), param.getValueAsString()));
                    }
                }
                //else if(multi!=null)multi.addParameter(param.getName(),param.getValueAsString());
            }
            // CGI
            else if (type.equals("cgi")) {
                if (param.getEncoded())
                    req.addHeader(HttpImpl.urlenc(param.getName(), charset),
                            HttpImpl.urlenc(param.getValueAsString(), charset));
                else
                    req.addHeader(param.getName(), param.getValueAsString());
            }
            // Header
            else if (type.startsWith("head")) {
                if (param.getName().equalsIgnoreCase("content-type"))
                    hasContentType = true;

                if (param.getName().equalsIgnoreCase("Content-Length")) {
                } else if (param.getName().equalsIgnoreCase("Accept-Encoding")) {
                    acceptEncoding.append(HttpImpl.headerValue(param.getValueAsString()));
                    acceptEncoding.append(", ");
                } else
                    req.addHeader(param.getName(), HttpImpl.headerValue(param.getValueAsString()));
            }
            // Cookie
            else if (type.equals("cookie")) {
                HTTPEngine4Impl.addCookie(client, host, param.getName(), param.getValueAsString(), "/",
                        charset);
            }
            // File
            else if (type.equals("file")) {
                hasForm = true;
                if (this.method == METHOD_GET)
                    throw new ApplicationException(
                            "httpparam type file can't only be used, when method of the tag http equal post");
                String strCT = HttpImpl.getContentType(param);
                ContentType ct = HTTPUtil.toContentType(strCT, null);

                String mt = "text/xml";
                if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true))
                    mt = ct.getMimeType();

                String cs = charset;
                if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true))
                    cs = ct.getCharset();

                if (doMultiPart) {
                    try {
                        Resource res = param.getFile();
                        parts.add(new FormBodyPart(param.getName(),
                                new ResourceBody(res, mt, res.getName(), cs)));
                        //parts.add(new ResourcePart(param.getName(),new ResourcePartSource(param.getFile()),getContentType(param),_charset));
                    } catch (FileNotFoundException e) {
                        throw new ApplicationException("can't upload file, path is invalid", e.getMessage());
                    }
                }
            }
            // XML
            else if (type.equals("xml")) {
                ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null);

                String mt = "text/xml";
                if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true))
                    mt = ct.getMimeType();

                String cs = charset;
                if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true))
                    cs = ct.getCharset();

                hasBody = true;
                hasContentType = true;
                req.addHeader("Content-type", mt + "; charset=" + cs);
                if (eem == null)
                    throw new ApplicationException("type xml is only supported for type post and put");
                HTTPEngine4Impl.setBody(eem, param.getValueAsString(), mt, cs);
            }
            // Body
            else if (type.equals("body")) {
                ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null);

                String mt = null;
                if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true))
                    mt = ct.getMimeType();

                String cs = charset;
                if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true))
                    cs = ct.getCharset();

                hasBody = true;
                if (eem == null)
                    throw new ApplicationException("type body is only supported for type post and put");
                HTTPEngine4Impl.setBody(eem, param.getValue(), mt, cs);

            } else {
                throw new ApplicationException("invalid type [" + type + "]");
            }

        }

        // post params
        if (postParam != null && postParam.size() > 0)
            post.setEntity(new org.apache.http.client.entity.UrlEncodedFormEntity(postParam, charset));

        if (compression) {
            acceptEncoding.append("gzip");
        } else {
            acceptEncoding.append("deflate;q=0");
            req.setHeader("TE", "deflate;q=0");
        }
        req.setHeader("Accept-Encoding", acceptEncoding.toString());

        // multipart
        if (doMultiPart && eem != null) {
            hasContentType = true;
            boolean doIt = true;
            if (!this.multiPart && parts.size() == 1) {
                ContentBody body = parts.get(0).getBody();
                if (body instanceof StringBody) {
                    StringBody sb = (StringBody) body;
                    try {
                        org.apache.http.entity.ContentType ct = org.apache.http.entity.ContentType
                                .create(sb.getMimeType(), sb.getCharset());
                        String str = IOUtil.toString(sb.getReader());
                        StringEntity entity = new StringEntity(str, ct);
                        eem.setEntity(entity);

                    } catch (IOException e) {
                        throw Caster.toPageException(e);
                    }
                    doIt = false;
                }
            }
            if (doIt) {
                MultipartEntity mpe = new MultipartEntity(HttpMultipartMode.STRICT);
                Iterator<FormBodyPart> it = parts.iterator();
                while (it.hasNext()) {
                    FormBodyPart part = it.next();
                    mpe.addPart(part.getName(), part.getBody());
                }
                eem.setEntity(mpe);
            }
            //eem.setRequestEntity(new MultipartRequestEntityFlex(parts.toArray(new Part[parts.size()]), eem.getParams(),http.multiPartType));
        }

        if (hasBody && hasForm)
            throw new ApplicationException("mixing httpparam  type file/formfield and body/XML is not allowed");

        if (!hasContentType) {
            if (isBinary) {
                if (hasBody)
                    req.addHeader("Content-type", "application/octet-stream");
                else
                    req.addHeader("Content-type", "application/x-www-form-urlencoded; charset=" + charset);
            } else {
                if (hasBody)
                    req.addHeader("Content-type", "text/html; charset=" + charset);
            }
        }

        // set User Agent
        if (!HttpImpl.hasHeaderIgnoreCase(req, "User-Agent"))
            req.setHeader("User-Agent", this.useragent);

        // set timeout
        if (this.timeout > 0L)
            HTTPEngine4Impl.setTimeout(params, (int) this.timeout);

        // set Username and Password
        if (this.username != null) {
            if (this.password == null)
                this.password = "";
            if (AUTH_TYPE_NTLM == this.authType) {
                if (StringUtil.isEmpty(this.workStation, true))
                    throw new ApplicationException(
                            "attribute workstation is required when authentication type is [NTLM]");
                if (StringUtil.isEmpty(this.domain, true))
                    throw new ApplicationException(
                            "attribute domain is required when authentication type is [NTLM]");

                HTTPEngine4Impl.setNTCredentials(client, this.username, this.password, this.workStation,
                        this.domain);
            } else
                httpContext = HTTPEngine4Impl.setCredentials(client, httpHost, this.username, this.password,
                        preauth);
        }

        // set Proxy
        ProxyData proxy = null;
        if (!StringUtil.isEmpty(this.proxyserver)) {
            proxy = ProxyDataImpl.getInstance(this.proxyserver, this.proxyport, this.proxyuser,
                    this.proxypassword);
        }
        if (pageContext.getConfig().isProxyEnableFor(host)) {
            proxy = pageContext.getConfig().getProxyData();
        }
        HTTPEngine4Impl.setProxy(client, req, proxy);

    }

    try {
        if (httpContext == null)
            httpContext = new BasicHttpContext();

        /////////////////////////////////////////// EXECUTE /////////////////////////////////////////////////
        Executor4 e = new Executor4(this, client, httpContext, req, redirect);
        HTTPResponse4Impl rsp = null;
        if (timeout < 0) {
            try {
                rsp = e.execute(httpContext);
            }

            catch (Throwable t) {
                if (!throwonerror) {
                    setUnknownHost(cfhttp, t);
                    return;
                }
                throw toPageException(t);

            }
        } else {
            e.start();
            try {
                synchronized (this) {//print.err(timeout);
                    this.wait(timeout);
                }
            } catch (InterruptedException ie) {
                throw Caster.toPageException(ie);
            }
            if (e.t != null) {
                if (!throwonerror) {
                    setUnknownHost(cfhttp, e.t);
                    return;
                }
                throw toPageException(e.t);
            }

            rsp = e.response;

            if (!e.done) {
                req.abort();
                if (throwonerror)
                    throw new HTTPException("408 Request Time-out", "a timeout occurred in tag http", 408,
                            "Time-out", rsp.getURL());
                setRequestTimeout(cfhttp);
                return;
                //throw new ApplicationException("timeout");   
            }
        }

        /////////////////////////////////////////// EXECUTE /////////////////////////////////////////////////
        Charset responseCharset = CharsetUtil.toCharset(rsp.getCharset());
        // Write Response Scope
        //String rawHeader=httpMethod.getStatusLine().toString();
        String mimetype = null;
        String contentEncoding = null;

        // status code
        cfhttp.set(STATUSCODE, ((rsp.getStatusCode() + " " + rsp.getStatusText()).trim()));
        cfhttp.set(STATUS_CODE, new Double(rsp.getStatusCode()));
        cfhttp.set(STATUS_TEXT, (rsp.getStatusText()));
        cfhttp.set(HTTP_VERSION, (rsp.getProtocolVersion()));

        //responseHeader
        lucee.commons.net.http.Header[] headers = rsp.getAllHeaders();
        StringBuffer raw = new StringBuffer(rsp.getStatusLine() + " ");
        Struct responseHeader = new StructImpl();
        Struct cookie;
        Array setCookie = new ArrayImpl();
        Query cookies = new QueryImpl(
                new String[] { "name", "value", "path", "domain", "expires", "secure", "httpOnly" }, 0,
                "cookies");

        for (int i = 0; i < headers.length; i++) {
            lucee.commons.net.http.Header header = headers[i];
            //print.ln(header);

            raw.append(header.toString() + " ");
            if (header.getName().equalsIgnoreCase("Set-Cookie")) {
                setCookie.append(header.getValue());
                parseCookie(cookies, header.getValue());
            } else {
                //print.ln(header.getName()+"-"+header.getValue());
                Object value = responseHeader.get(KeyImpl.getInstance(header.getName()), null);
                if (value == null)
                    responseHeader.set(KeyImpl.getInstance(header.getName()), header.getValue());
                else {
                    Array arr = null;
                    if (value instanceof Array) {
                        arr = (Array) value;
                    } else {
                        arr = new ArrayImpl();
                        responseHeader.set(KeyImpl.getInstance(header.getName()), arr);
                        arr.appendEL(value);
                    }
                    arr.appendEL(header.getValue());
                }
            }

            // Content-Type
            if (header.getName().equalsIgnoreCase("Content-Type")) {
                mimetype = header.getValue();
                if (mimetype == null)
                    mimetype = NO_MIMETYPE;
            }

            // Content-Encoding
            if (header.getName().equalsIgnoreCase("Content-Encoding")) {
                contentEncoding = header.getValue();
            }

        }
        cfhttp.set(RESPONSEHEADER, responseHeader);
        cfhttp.set(KeyConstants._cookies, cookies);
        responseHeader.set(STATUS_CODE, new Double(rsp.getStatusCode()));
        responseHeader.set(EXPLANATION, (rsp.getStatusText()));
        if (setCookie.size() > 0)
            responseHeader.set(SET_COOKIE, setCookie);

        // is text 
        boolean isText = mimetype == null || mimetype == NO_MIMETYPE || HTTPUtil.isTextMimeType(mimetype);

        // is multipart 
        boolean isMultipart = MultiPartResponseUtils.isMultipart(mimetype);

        cfhttp.set(KeyConstants._text, Caster.toBoolean(isText));

        // mimetype charset
        //boolean responseProvideCharset=false;
        if (!StringUtil.isEmpty(mimetype, true)) {
            if (isText) {
                String[] types = HTTPUtil.splitMimeTypeAndCharset(mimetype, null);
                if (types[0] != null)
                    cfhttp.set(KeyConstants._mimetype, types[0]);
                if (types[1] != null)
                    cfhttp.set(CHARSET, types[1]);

            } else
                cfhttp.set(KeyConstants._mimetype, mimetype);
        } else
            cfhttp.set(KeyConstants._mimetype, NO_MIMETYPE);

        // File
        Resource file = null;

        if (strFile != null && strPath != null) {
            file = ResourceUtil.toResourceNotExisting(pageContext, strPath).getRealResource(strFile);
        } else if (strFile != null) {
            file = ResourceUtil.toResourceNotExisting(pageContext, strFile);
        } else if (strPath != null) {
            file = ResourceUtil.toResourceNotExisting(pageContext, strPath);
            //Resource dir = file.getParentResource();
            if (file.isDirectory()) {
                file = file.getRealResource(req.getURI().getPath());// TODO was getName() ->http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/URI.html#getName()
            }

        }
        if (file != null)
            pageContext.getConfig().getSecurityManager().checkFileLocation(file);

        // filecontent
        InputStream is = null;
        if (isText && getAsBinary != GET_AS_BINARY_YES) {
            String str;
            try {

                // read content
                if (method != METHOD_HEAD) {
                    is = rsp.getContentAsStream();
                    if (is != null && HttpImpl.isGzipEncoded(contentEncoding))
                        is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is)
                                : new GZIPInputStream(is);
                }
                try {
                    try {
                        str = is == null ? "" : IOUtil.toString(is, responseCharset);
                    } catch (EOFException eof) {
                        if (is instanceof CachingGZIPInputStream) {
                            str = IOUtil.toString(is = ((CachingGZIPInputStream) is).getRawData(),
                                    responseCharset);
                        } else
                            throw eof;
                    }
                } catch (UnsupportedEncodingException uee) {
                    str = IOUtil.toString(is, (Charset) null);
                }
            } catch (IOException ioe) {
                throw Caster.toPageException(ioe);
            } finally {
                IOUtil.closeEL(is);
            }

            if (str == null)
                str = "";
            if (resolveurl) {
                //if(e.redirectURL!=null)url=e.redirectURL.toExternalForm();
                str = new URLResolver().transform(str, e.response.getTargetURL(), false);
            }
            cfhttp.set(FILE_CONTENT, str);
            try {
                if (file != null) {
                    IOUtil.write(file, str, ((PageContextImpl) pageContext).getWebCharset(), false);
                }
            } catch (IOException e1) {
            }

            if (name != null) {
                Query qry = CSVParser.toQuery(str, delimiter, textqualifier, columns, firstrowasheaders);
                pageContext.setVariable(name, qry);
            }
        }
        // Binary
        else {
            byte[] barr = null;
            if (HttpImpl.isGzipEncoded(contentEncoding)) {
                if (method != METHOD_HEAD) {
                    is = rsp.getContentAsStream();
                    is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is) : new GZIPInputStream(is);
                }

                try {
                    try {
                        barr = is == null ? new byte[0] : IOUtil.toBytes(is);
                    } catch (EOFException eof) {
                        if (is instanceof CachingGZIPInputStream)
                            barr = IOUtil.toBytes(((CachingGZIPInputStream) is).getRawData());
                        else
                            throw eof;
                    }
                } catch (IOException t) {
                    throw Caster.toPageException(t);
                } finally {
                    IOUtil.closeEL(is);
                }
            } else {
                try {
                    if (method != METHOD_HEAD)
                        barr = rsp.getContentAsByteArray();
                    else
                        barr = new byte[0];
                } catch (IOException t) {
                    throw Caster.toPageException(t);
                }
            }
            //IF Multipart response get file content and parse parts
            if (barr != null) {
                if (isMultipart) {
                    cfhttp.set(FILE_CONTENT, MultiPartResponseUtils.getParts(barr, mimetype));
                } else {
                    cfhttp.set(FILE_CONTENT, barr);
                }
            } else
                cfhttp.set(FILE_CONTENT, "");

            if (file != null) {
                try {
                    if (barr != null)
                        IOUtil.copy(new ByteArrayInputStream(barr), file, true);
                } catch (IOException ioe) {
                    throw Caster.toPageException(ioe);
                }
            }
        }

        // header      
        cfhttp.set(KeyConstants._header, raw.toString());
        if (!HttpImpl.isStatusOK(rsp.getStatusCode())) {
            String msg = rsp.getStatusCode() + " " + rsp.getStatusText();
            cfhttp.setEL(ERROR_DETAIL, msg);
            if (throwonerror) {
                throw new HTTPException(msg, null, rsp.getStatusCode(), rsp.getStatusText(), rsp.getURL());
            }
        }
    } finally {
        //rsp.release();
    }

}