Example usage for org.apache.commons.httpclient.params HttpMethodParams setSoTimeout

List of usage examples for org.apache.commons.httpclient.params HttpMethodParams setSoTimeout

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpMethodParams setSoTimeout.

Prototype

public void setSoTimeout(int paramInt) 

Source Link

Usage

From source file:com.taobao.diamond.client.impl.DefaultDiamondPublisher.java

private void configureHttpMethod(HttpMethod method) {
    // socket//from  w ww .  j  a v  a2  s .c  om
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout(Constants.ONCE_TIMEOUT);
    method.setParams(params);
}

From source file:de.innovationgate.wgpublisher.webtml.Include.java

private void performURLInclude() throws TMLException {

    Status status = (Status) getStatus();

    try {// w w w  .j a v a 2s .co  m

        HttpClient client = WGFactory.getHttpClientFactory().createHttpClient();
        HttpMethodParams methodParams = new HttpMethodParams();
        methodParams.setSoTimeout(Integer.parseInt(getTimeout()));
        methodParams.setVersion(HttpVersion.HTTP_1_1);

        GetMethod getMethod = new GetMethod();
        getMethod.setURI(new URI(status.ref, false));
        getMethod.setParams(methodParams);
        getMethod.setFollowRedirects(true);

        int httpStatus = client.executeMethod(getMethod);
        if (httpStatus != HttpServletResponse.SC_OK) {
            throw new TMLException("Response status " + httpStatus + " (" + getMethod.getStatusText()
                    + ") for included URL " + ref, true);
        }

        String encoding = getEncoding();
        if (encoding == null) {
            encoding = getMethod.getResponseCharSet();
            if (encoding == null) {
                getTMLContext().addwarning("No encoding returned from URL '" + status.ref
                        + "'. Assuming default encoding " + encoding);
                encoding = getCore().getCharacterEncoding();
            }
        }

        Reader reader = new InputStreamReader(getMethod.getResponseBodyAsStream(), encoding);
        StringWriter writer = new StringWriter();
        char[] buf = new char[2048];
        long count = 0;

        String limitStr = getLimit();
        long charLimit = 0;
        try {
            charLimit = Math.round(1024 * 1024 * Double.parseDouble(limitStr));
        } catch (NumberFormatException e) {
            throw new TMLException("Cannot parse limit attribute as number: " + limitStr);
        }

        int len;
        while ((len = reader.read(buf)) != -1) {
            writer.write(buf, 0, len);
            count += len;
            if (charLimit != 0 && count > charLimit) {
                throw new TMLException("Include of URL '" + status.ref + "' reaches content limit of "
                        + limitStr + " million characters. Include is cancelled.");
            }
        }
        this.setResult(writer.toString());

    } catch (java.io.IOException exc) {
        log.error("Exception including url", exc);
        this.addWarning("Exception while including url: " + exc.getMessage());
    }

}

From source file:com.xmlcalabash.library.ApacheHttpRequest.java

public void run() throws SaxonApiException {
    super.run();/*from   ww  w.ja va2  s. c  om*/

    XdmNode requestDoc = source.read();
    XdmNode start = S9apiUtils.getDocumentElement(requestDoc);

    if (!c_request.equals(start.getNodeName())) {
        throw new UnsupportedOperationException("Not a c:http-request!");
    }

    // Check for valid attributes
    XdmSequenceIterator iter = start.axisIterator(Axis.ATTRIBUTE);
    boolean ok = true;
    while (iter.hasNext()) {
        XdmNode attr = (XdmNode) iter.next();
        QName name = attr.getNodeName();
        if (_method.equals(name) || _href.equals(name) || _detailed.equals(name) || _status_only.equals(name)
                || _username.equals(name) || _password.equals(name) || _auth_method.equals(name)
                || _send_authorization.equals(name) || _override_content_type.equals(name)) {
            // nop
        } else {
            if (XMLConstants.DEFAULT_NS_PREFIX.equals(name.getNamespaceURI())) {
                throw new XProcException("Unsupported attribute on c:http-request: " + name);
            }
        }
    }

    method = start.getAttributeValue(_method);
    statusOnly = "true".equals(start.getAttributeValue(_status_only));
    detailed = "true".equals(start.getAttributeValue(_detailed));
    overrideContentType = start.getAttributeValue(_override_content_type);

    if (start.getAttributeValue(_href) == null) {
        throw new XProcException("The 'href' attribute must be specified on p:http-request");
    }

    requestURI = start.getBaseURI().resolve(start.getAttributeValue(_href));

    if ("file".equals(requestURI.getScheme())) {
        doFile();
        return;
    }

    client = new HttpClient();

    String timeOutStr = step.getExtensionAttribute(cx_timeout);
    if (timeOutStr != null) {
        HttpMethodParams params = client.getParams();
        params.setSoTimeout(Integer.parseInt(timeOutStr));
    }

    ProxySelector proxySelector = ProxySelector.getDefault();
    List<Proxy> plist = proxySelector.select(requestURI);
    // I have no idea what I'm expected to do if I get more than one...
    if (plist.size() > 0) {
        Proxy proxy = plist.get(0);
        switch (proxy.type()) {
        case DIRECT:
            // nop;
            break;
        case HTTP:
            // This can't cause a ClassCastException, right?
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            String host = addr.getHostName();
            int port = addr.getPort();
            client.getHostConfiguration().setProxy(host, port);
            break;
        default:
            // FIXME: send out a log message
            break;
        }
    }

    if (start.getAttributeValue(_username) != null) {
        String user = start.getAttributeValue(_username);
        String pass = start.getAttributeValue(_password);
        String meth = start.getAttributeValue(_auth_method);

        if (meth == null || !("basic".equals(meth.toLowerCase()) || "digest".equals(meth.toLowerCase()))) {
            throw XProcException.stepError(3, "Unsupported auth-method: " + meth);
        }

        String host = requestURI.getHost();
        int port = requestURI.getPort();
        AuthScope scope = new AuthScope(host, port);

        UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, pass);

        client.getState().setCredentials(scope, cred);
    }

    iter = start.axisIterator(Axis.CHILD);
    XdmNode body = null;
    while (iter.hasNext()) {
        XdmNode event = (XdmNode) iter.next();
        // FIXME: What about non-whitespace text nodes?
        if (event.getNodeKind() == XdmNodeKind.ELEMENT) {
            if (body != null) {
                throw new UnsupportedOperationException("Elements follow c:multipart or c:body");
            }

            if (XProcConstants.c_header.equals(event.getNodeName())) {
                headers.add(new Header(event.getAttributeValue(_name), event.getAttributeValue(_value)));
            } else if (XProcConstants.c_multipart.equals(event.getNodeName())
                    || XProcConstants.c_body.equals(event.getNodeName())) {
                body = event;
            } else {
                throw new UnsupportedOperationException("Unexpected request element: " + event.getNodeName());
            }
        }
    }

    HttpMethodBase httpResult;

    if (method == null) {
        throw new XProcException("Method must be specified.");
    }

    if ("get".equals(method.toLowerCase())) {
        httpResult = doGet();
    } else if ("post".equals(method.toLowerCase())) {
        httpResult = doPost(body);
    } else if ("put".equals(method.toLowerCase())) {
        httpResult = doPut(body);
    } else if ("head".equals(method.toLowerCase())) {
        httpResult = doHead();
    } else {
        throw new UnsupportedOperationException("Unrecognized http method: " + method);
    }

    TreeWriter tree = new TreeWriter(runtime);
    tree.startDocument(requestURI);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(httpResult);

        String contentType = getContentType(httpResult);
        if (overrideContentType != null) {
            if ((xmlContentType(contentType) && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("text/") && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("image/") && xmlContentType(overrideContentType))
                    || (contentType.startsWith("image/") && overrideContentType.startsWith("text/"))
                    || (contentType.startsWith("multipart/") && !overrideContentType.startsWith("multipart/"))
                    || (!contentType.startsWith("multipart/")
                            && overrideContentType.startsWith("multipart/"))) {
                throw XProcException.stepError(30);
            }

            //System.err.println(overrideContentType + " overrides " + contentType);
            contentType = overrideContentType;
        }

        if (detailed) {
            tree.addStartElement(XProcConstants.c_response);
            tree.addAttribute(_status, "" + statusCode);
            tree.startContent();

            for (Header header : httpResult.getResponseHeaders()) {
                // I don't understand why/how HeaderElement parsing works. I get very weird results.
                // So I'm just going to go the long way around...
                String h = header.toString();
                int cp = h.indexOf(":");
                String name = header.getName();
                String value = h.substring(cp + 1).trim();

                tree.addStartElement(XProcConstants.c_header);
                tree.addAttribute(_name, name);
                tree.addAttribute(_value, value);
                tree.startContent();
                tree.addEndElement();
            }

            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                readBodyContent(tree, bodyStream, httpResult);
            }

            tree.addEndElement();
        } else {
            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                readBodyContent(tree, bodyStream, httpResult);
            }
        }
    } catch (Exception e) {
        throw new XProcException(e);
    } finally {
        // Release the connection.
        httpResult.releaseConnection();
    }

    tree.endDocument();

    XdmNode resultNode = tree.getResult();

    result.write(resultNode);
}

From source file:com.taobao.diamond.client.impl.DefaultDiamondSubscriber.java

private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut,
        HttpMethod httpMethod) {//ww w. jav a 2s. c  o  m
    if (skipContentCache && null != cacheData) {
        if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) {
            httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader());
        }
        if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) {
            httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5());
        }
    }

    httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate");

    // HttpMethod
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout((int) onceTimeOut);
    // ///////////////////////
    httpMethod.setParams(params);
    httpClient.getHostConfiguration().setHost(
            diamondConfigure.getDomainNameList().get(this.domainNamePos.get()), diamondConfigure.getPort());
}

From source file:cn.leancloud.diamond.client.impl.DefaultDiamondSubscriber.java

private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut,
        HttpMethod httpMethod) {/*ww w.java 2s .co m*/
    if (skipContentCache && null != cacheData) {
        if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) {
            httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader());
        }
        if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) {
            httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5());
        }
    }

    httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate");

    // HttpMethod?
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout((int) onceTimeOut);
    // ///////////////////////
    httpMethod.setParams(params);
    httpClient.getHostConfiguration().setHost(
            diamondConfigure.getDomainNameList().get(this.domainNamePos.get()), diamondConfigure.getPort());
}

From source file:com.taobao.diamond.client.impl.DefaultDiamondSubscriber.java

/**
 * DiamondServerDataID//  www. j  av a2 s  . c om
 * 
 * @param timeout
 * @return
 */
Set<String> checkUpdateDataIds(long timeout) {
    if (!isRun) {
        throw new RuntimeException("DiamondSubscriberDataID");
    }
    // ==============================================
    if (MockServer.isTestMode()) {
        return testData();
    }
    // ==========================================================
    long waitTime = 0;

    // Set<String> localModifySet = getLocalUpdateDataIds();
    String probeUpdateString = getProbeUpdateString();
    if (StringUtils.isBlank(probeUpdateString)) {
        return null;
    }

    while (0 == timeout || timeout > waitTime) {
        // 
        long onceTimeOut = getOnceTimeOut(waitTime, timeout);
        waitTime += onceTimeOut;

        PostMethod postMethod = new PostMethod(Constants.HTTP_URI_FILE);

        postMethod.addParameter(Constants.PROBE_MODIFY_REQUEST, probeUpdateString);

        // HttpMethod
        HttpMethodParams params = new HttpMethodParams();
        params.setSoTimeout((int) onceTimeOut);
        // ///////////////////////
        postMethod.setParams(params);

        try {
            httpClient.getHostConfiguration().setHost(
                    diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
                    this.diamondConfigure.getPort());

            int httpStatus = httpClient.executeMethod(postMethod);

            switch (httpStatus) {
            case SC_OK: {
                Set<String> result = getUpdateDataIds(postMethod);
                return result;
            }

            case SC_SERVICE_UNAVAILABLE: {
                rotateToNextDomain();
            }
                break;

            default: {
                log.warn("DataIDHTTP State: " + httpStatus);
                rotateToNextDomain();
            }
            }
        } catch (HttpException e) {
            log.error("Http", e);
            rotateToNextDomain();
        } catch (IOException e) {
            log.error("IO", e);
            rotateToNextDomain();
        } catch (Exception e) {
            log.error("", e);
            rotateToNextDomain();
        } finally {
            postMethod.releaseConnection();
        }
    }
    throw new RuntimeException("DataID "
            + diamondConfigure.getDomainNameList().get(this.domainNamePos.get()) + ", " + timeout);
}

From source file:cn.leancloud.diamond.client.impl.DefaultDiamondSubscriber.java

/**
 * DiamondServer??DataID/*from   ww  w . ja v a 2 s .  c  o m*/
 * 
 * @param timeout
 * @return
 */
Set<String> checkUpdateDataIds(long timeout) {
    if (!isRun) {
        throw new RuntimeException(
                "DiamondSubscriber????DataID");
    }
    // =======================?=======================
    if (MockServer.isTestMode()) {
        return testData();
    }
    // ==========================================================
    long waitTime = 0;

    // Set<String> localModifySet = getLocalUpdateDataIds();
    String probeUpdateString = getProbeUpdateString();
    if (StringUtils.isBlank(probeUpdateString)) {
        return null;
    }

    while (0 == timeout || timeout > waitTime) {
        // 
        long onceTimeOut = getOnceTimeOut(waitTime, timeout);
        waitTime += onceTimeOut;

        PostMethod postMethod = new PostMethod(Constants.HTTP_URI_FILE);

        postMethod.addParameter(Constants.PROBE_MODIFY_REQUEST, probeUpdateString);

        // HttpMethod?
        HttpMethodParams params = new HttpMethodParams();
        params.setSoTimeout((int) onceTimeOut);
        // ///////////////////////
        postMethod.setParams(params);

        try {
            httpClient.getHostConfiguration().setHost(
                    diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
                    this.diamondConfigure.getPort());

            int httpStatus = httpClient.executeMethod(postMethod);

            log.info(httpStatus);

            switch (httpStatus) {
            case SC_OK: {
                Set<String> result = getUpdateDataIds(postMethod);
                return result;
            }

            case SC_SERVICE_UNAVAILABLE: {
                rotateToNextDomain();
            }
                break;

            default: {
                log.warn("?DataIDHTTP State: " + httpStatus);
                rotateToNextDomain();
            }
            }
        } catch (HttpException e) {
            log.error("???Http", e);
            rotateToNextDomain();
        } catch (IOException e) {
            log.error("???IO", e);
            rotateToNextDomain();
        } catch (Exception e) {
            log.error("", e);
            rotateToNextDomain();
        } finally {
            postMethod.releaseConnection();
        }
    }
    throw new RuntimeException("?DataID "
            + diamondConfigure.getDomainNameList().get(this.domainNamePos.get()) + ", "
            + timeout);
}

From source file:com.mengka.diamond.client.impl.DefaultDiamondSubscriber.java

/**
 * DiamondServer??DataID/*w w  w.j  a  v a  2s.  c  om*/
 * 
 * @param timeout
 * @return
 */
Set<String> checkUpdateDataIds(long timeout) {
    if (!isRun) {
        throw new RuntimeException(
                "DiamondSubscriber????DataID");
    }
    // =======================?=======================
    if (MockServer.isTestMode()) {
        return testData();
    }
    // ==========================================================
    long waitTime = 0;

    // Set<String> localModifySet = getLocalUpdateDataIds();
    String probeUpdateString = getProbeUpdateString();
    if (StringUtils.isBlank(probeUpdateString)) {
        return null;
    }

    while (0 == timeout || timeout > waitTime) {
        // 
        long onceTimeOut = getOnceTimeOut(waitTime, timeout);
        waitTime += onceTimeOut;

        PostMethod postMethod = new PostMethod(Constants.CONFIG_HTTP_URI_FILE);

        postMethod.addParameter(Constants.PROBE_MODIFY_REQUEST, probeUpdateString);

        // HttpMethod?
        HttpMethodParams params = new HttpMethodParams();
        params.setSoTimeout((int) onceTimeOut);
        // ///////////////////////
        postMethod.setParams(params);

        try {
            httpClient.getHostConfiguration().setHost(
                    diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
                    this.diamondConfigure.getPort());

            int httpStatus = httpClient.executeMethod(postMethod);

            switch (httpStatus) {
            case SC_OK: {
                Set<String> result = getUpdateDataIds(postMethod);
                return result;
            }

            case SC_SERVICE_UNAVAILABLE: {
                rotateToNextDomain();
            }
                break;

            default: {
                log.warn("?DataIDHTTP State: " + httpStatus);
                rotateToNextDomain();
            }
            }
        } catch (HttpException e) {
            log.error("???Http", e);
            rotateToNextDomain();
        } catch (IOException e) {
            log.error("???IO", e);
            rotateToNextDomain();
        } catch (Exception e) {
            log.error("", e);
            rotateToNextDomain();
        } finally {
            postMethod.releaseConnection();
        }
    }
    throw new RuntimeException("?DataID "
            + diamondConfigure.getDomainNameList().get(this.domainNamePos.get()) + ", "
            + timeout);
}

From source file:com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.java

@Override
public void executeMethod(final HttpMethod method, final ClientRequest cr) {
    final Map<String, Object> props = cr.getProperties();

    method.setDoAuthentication(true);/*from w ww .ja  va 2 s .  c o  m*/

    final HttpMethodParams methodParams = method.getParams();

    // Set the handle cookies property
    if (!cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES)) {
        methodParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    }

    // Set the interactive and credential provider properties
    if (cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_INTERACTIVE)) {
        CredentialsProvider provider = (CredentialsProvider) props
                .get(ApacheHttpClientConfig.PROPERTY_CREDENTIALS_PROVIDER);
        if (provider == null) {
            provider = DEFAULT_CREDENTIALS_PROVIDER;
        }
        methodParams.setParameter(CredentialsProvider.PROVIDER, provider);
    } else {
        methodParams.setParameter(CredentialsProvider.PROVIDER, null);
    }

    // Set the read timeout
    final Integer readTimeout = (Integer) props.get(ApacheHttpClientConfig.PROPERTY_READ_TIMEOUT);
    if (readTimeout != null) {
        methodParams.setSoTimeout(readTimeout);
    }

    if (method instanceof EntityEnclosingMethod) {
        final EntityEnclosingMethod entMethod = (EntityEnclosingMethod) method;

        if (cr.getEntity() != null) {
            final RequestEntityWriter re = getRequestEntityWriter(cr);
            final Integer chunkedEncodingSize = (Integer) props
                    .get(ApacheHttpClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE);
            if (chunkedEncodingSize != null) {
                // There doesn't seems to be a way to set the chunk size.
                entMethod.setContentChunked(true);

                // It is not possible for a MessageBodyWriter to modify
                // the set of headers before writing out any bytes to
                // the OutputStream
                // This makes it impossible to use the multipart
                // writer that modifies the content type to add a boundary
                // parameter
                writeOutBoundHeaders(cr.getHeaders(), method);

                // Do not buffer the request entity when chunked encoding is
                // set
                entMethod.setRequestEntity(new RequestEntity() {

                    @Override
                    public boolean isRepeatable() {
                        return false;
                    }

                    @Override
                    public void writeRequest(OutputStream out) throws IOException {
                        re.writeRequestEntity(out);
                    }

                    @Override
                    public long getContentLength() {
                        return re.getSize();
                    }

                    @Override
                    public String getContentType() {
                        return re.getMediaType().toString();
                    }
                });

            } else {
                entMethod.setContentChunked(false);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    re.writeRequestEntity(new CommittingOutputStream(baos) {

                        @Override
                        protected void commit() throws IOException {
                            writeOutBoundHeaders(cr.getMetadata(), method);
                        }
                    });
                } catch (IOException ex) {
                    throw new ClientHandlerException(ex);
                }

                final byte[] content = baos.toByteArray();
                entMethod.setRequestEntity(new RequestEntity() {

                    @Override
                    public boolean isRepeatable() {
                        return true;
                    }

                    @Override
                    public void writeRequest(OutputStream out) throws IOException {
                        out.write(content);
                    }

                    @Override
                    public long getContentLength() {
                        return content.length;
                    }

                    @Override
                    public String getContentType() {
                        return re.getMediaType().toString();
                    }
                });
            }
        } else {
            writeOutBoundHeaders(cr.getHeaders(), method);
        }
    } else {
        writeOutBoundHeaders(cr.getHeaders(), method);

        // Follow redirects
        method.setFollowRedirects(cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_FOLLOW_REDIRECTS));
    }
    try {
        httpClient.executeMethod(getHostConfiguration(httpClient, props), method, getHttpState(props));
    } catch (Exception e) {
        method.releaseConnection();
        throw new ClientHandlerException(e);
    }
}

From source file:com.xmlcalabash.library.HttpRequest.java

public void gorun() throws SaxonApiException {
    super.gorun();

    XdmNode requestDoc = source.read(stepContext);
    XdmNode start = S9apiUtils.getDocumentElement(requestDoc);

    if (!c_request.equals(start.getNodeName())) {
        throw XProcException.stepError(40);
    }/*  w  w  w . j  ava 2 s.  com*/

    // Check for valid attributes
    XdmSequenceIterator iter = start.axisIterator(Axis.ATTRIBUTE);
    boolean ok = true;
    while (iter.hasNext()) {
        XdmNode attr = (XdmNode) iter.next();
        QName name = attr.getNodeName();
        if (_method.equals(name) || _href.equals(name) || _detailed.equals(name) || _status_only.equals(name)
                || _username.equals(name) || _password.equals(name) || _auth_method.equals(name)
                || _send_authorization.equals(name) || _override_content_type.equals(name)) {
            // nop
        } else {
            if (XMLConstants.DEFAULT_NS_PREFIX.equals(name.getNamespaceURI())) {
                throw new XProcException(step.getNode(),
                        "Unsupported attribute on c:request for p:http-request: " + name);
            }
        }
    }

    String send = step.getExtensionAttribute(cx_send_binary);
    encodeBinary = !"true".equals(send);

    method = start.getAttributeValue(_method);
    statusOnly = "true".equals(start.getAttributeValue(_status_only));
    detailed = "true".equals(start.getAttributeValue(_detailed));
    overrideContentType = start.getAttributeValue(_override_content_type);

    if (method == null) {
        throw XProcException.stepError(6);
    }

    if (statusOnly && !detailed) {
        throw XProcException.stepError(4);
    }

    if (start.getAttributeValue(_href) == null) {
        throw new XProcException(step.getNode(),
                "The 'href' attribute must be specified on c:request for p:http-request");
    }

    requestURI = start.getBaseURI().resolve(start.getAttributeValue(_href));

    if ("file".equals(requestURI.getScheme())) {
        doFile();
        return;
    }

    // What about cookies
    String saveCookieKey = step.getExtensionAttribute(cx_save_cookies);
    String useCookieKeys = step.getExtensionAttribute(cx_use_cookies);
    String cookieKey = step.getExtensionAttribute(cx_cookies);

    if (saveCookieKey == null) {
        saveCookieKey = cookieKey;
    }

    if (useCookieKeys == null) {
        useCookieKeys = cookieKey;
    }

    client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    client.getParams().setParameter("http.protocol.single-cookie-header", true);

    HttpState state = client.getState();

    if (useCookieKeys != null) {
        for (String key : useCookieKeys.split("\\s+")) {
            for (Cookie cookie : runtime.getCookies(key)) {
                state.addCookie(cookie);
            }
        }
    }

    String timeOutStr = step.getExtensionAttribute(cx_timeout);
    if (timeOutStr != null) {
        HttpMethodParams params = client.getParams();
        params.setSoTimeout(Integer.parseInt(timeOutStr));
    }

    ProxySelector proxySelector = ProxySelector.getDefault();
    List<Proxy> plist = proxySelector.select(requestURI);
    // I have no idea what I'm expected to do if I get more than one...
    if (plist.size() > 0) {
        Proxy proxy = plist.get(0);
        switch (proxy.type()) {
        case DIRECT:
            // nop;
            break;
        case HTTP:
            // This can't cause a ClassCastException, right?
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            String host = addr.getHostName();
            int port = addr.getPort();
            client.getHostConfiguration().setProxy(host, port);
            break;
        default:
            // FIXME: send out a log message
            break;
        }
    }

    if (start.getAttributeValue(_username) != null) {
        String user = start.getAttributeValue(_username);
        String pass = start.getAttributeValue(_password);
        String meth = start.getAttributeValue(_auth_method);

        if (meth == null || !("basic".equals(meth.toLowerCase()) || "digest".equals(meth.toLowerCase()))) {
            throw XProcException.stepError(3, "Unsupported auth-method: " + meth);
        }

        String host = requestURI.getHost();
        int port = requestURI.getPort();
        AuthScope scope = new AuthScope(host, port);

        UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, pass);

        client.getState().setCredentials(scope, cred);

        if ("basic".equals(meth.toLowerCase())) {
            client.getParams().setAuthenticationPreemptive(true);
        }
    }

    iter = start.axisIterator(Axis.CHILD);
    XdmNode body = null;
    while (iter.hasNext()) {
        XdmNode event = (XdmNode) iter.next();
        // FIXME: What about non-whitespace text nodes?
        if (event.getNodeKind() == XdmNodeKind.ELEMENT) {
            if (body != null) {
                throw new UnsupportedOperationException("Elements follow c:multipart or c:body");
            }

            if (XProcConstants.c_header.equals(event.getNodeName())) {
                String name = event.getAttributeValue(_name);
                if (name == null) {
                    continue; // this can't happen, right?
                }
                if (name.toLowerCase().equals("content-type")) {
                    // We'll deal with the content-type header later
                    headerContentType = event.getAttributeValue(_value).toLowerCase();
                } else {
                    headers.add(new Header(event.getAttributeValue(_name), event.getAttributeValue(_value)));
                }
            } else if (XProcConstants.c_multipart.equals(event.getNodeName())
                    || XProcConstants.c_body.equals(event.getNodeName())) {
                body = event;
            } else {
                throw new UnsupportedOperationException("Unexpected request element: " + event.getNodeName());
            }
        }
    }

    String lcMethod = method.toLowerCase();

    // You can only have a body on PUT or POST
    if (body != null && !("put".equals(lcMethod) || "post".equals(lcMethod))) {
        throw XProcException.stepError(5);
    }

    HttpMethodBase httpResult;

    if ("get".equals(lcMethod)) {
        httpResult = doGet();
    } else if ("post".equals(lcMethod)) {
        httpResult = doPost(body);
    } else if ("put".equals(lcMethod)) {
        httpResult = doPut(body);
    } else if ("head".equals(lcMethod)) {
        httpResult = doHead();
    } else if ("delete".equals(lcMethod)) {
        httpResult = doDelete();
    } else {
        throw new UnsupportedOperationException("Unrecognized http method: " + method);
    }

    TreeWriter tree = new TreeWriter(runtime);
    tree.startDocument(requestURI);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(httpResult);

        // Deal with cookies
        if (saveCookieKey != null) {
            runtime.clearCookies(saveCookieKey);

            state = client.getState();
            Cookie[] cookies = state.getCookies();
            for (Cookie cookie : cookies) {
                runtime.addCookie(saveCookieKey, cookie);
            }
        }

        String contentType = getContentType(httpResult);
        if (overrideContentType != null) {
            if ((xmlContentType(contentType) && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("text/") && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("image/") && xmlContentType(overrideContentType))
                    || (contentType.startsWith("image/") && overrideContentType.startsWith("text/"))
                    || (contentType.startsWith("multipart/") && !overrideContentType.startsWith("multipart/"))
                    || (!contentType.startsWith("multipart/")
                            && overrideContentType.startsWith("multipart/"))) {
                throw XProcException.stepError(30);
            }

            //System.err.println(overrideContentType + " overrides " + contentType);
            contentType = overrideContentType;
        }

        if (detailed) {
            tree.addStartElement(XProcConstants.c_response);
            tree.addAttribute(_status, "" + statusCode);
            tree.startContent();

            for (Header header : httpResult.getResponseHeaders()) {
                // I don't understand why/how HeaderElement parsing works. I get very weird results.
                // So I'm just going to go the long way around...
                String h = header.toString();
                int cp = h.indexOf(":");
                String name = header.getName();
                String value = h.substring(cp + 1).trim();

                tree.addStartElement(XProcConstants.c_header);
                tree.addAttribute(_name, name);
                tree.addAttribute(_value, value);
                tree.startContent();
                tree.addEndElement();
            }

            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                if (bodyStream != null) {
                    readBodyContent(tree, bodyStream, httpResult);
                }
            }

            tree.addEndElement();
        } else {
            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                if (bodyStream != null) {
                    readBodyContent(tree, bodyStream, httpResult);
                } else {
                    throw XProcException.dynamicError(6);
                }
            }
        }
    } catch (Exception e) {
        throw new XProcException(e);
    } finally {
        // Release the connection.
        httpResult.releaseConnection();
    }

    tree.endDocument();

    XdmNode resultNode = tree.getResult();

    result.write(stepContext, resultNode);
}