Example usage for java.net ProxySelector select

List of usage examples for java.net ProxySelector select

Introduction

In this page you can find the example usage for java.net ProxySelector select.

Prototype

public abstract List<Proxy> select(URI uri);

Source Link

Document

Selects all the applicable proxies based on the protocol to access the resource with and a destination address to access the resource at.

Usage

From source file:org.mozilla.mozstumbler.service.core.http.HttpUtil.java

private URLConnection openConnectionWithProxy(URL url) throws IOException {
    Proxy proxy = Proxy.NO_PROXY;

    ProxySelector proxySelector = ProxySelector.getDefault();
    if (proxySelector != null) {
        URI uri;/*  w  ww .  ja v  a 2 s  .c  om*/
        try {
            uri = url.toURI();
        } catch (URISyntaxException e) {
            IOException ioe = new IOException(url.toString());
            ioe.initCause(e);
            throw ioe;
        }

        List<Proxy> proxies = proxySelector.select(uri);
        if (proxies != null && !proxies.isEmpty()) {
            proxy = proxies.get(0);
        }
    }

    return url.openConnection(proxy);
}

From source file:org.whitesource.agent.client.WssServiceClientImpl.java

private void findDefaultProxy() {
    ProxySearch proxySearch = new ProxySearch();
    proxySearch.addStrategy(ProxySearch.Strategy.JAVA);
    proxySearch.addStrategy(ProxySearch.Strategy.ENV_VAR);
    proxySearch.addStrategy(ProxySearch.Strategy.OS_DEFAULT);
    proxySearch.addStrategy(ProxySearch.Strategy.BROWSER);
    ProxySelector proxySelector = proxySearch.getProxySelector();

    if (proxySelector != null) {
        ProxySelector.setDefault(proxySelector);
        try {//from   www .  jav a2s . c om
            List<Proxy> proxyList = proxySelector.select(new URI(serviceUrl));
            if (proxyList != null && !proxyList.isEmpty()) {
                for (Proxy proxy : proxyList) {
                    InetSocketAddress address = (InetSocketAddress) proxy.address();
                    if (address != null) {
                        String host = address.getHostName();
                        int port = address.getPort();
                        String username = System.getProperty(HTTP_PROXY_USER);
                        String password = System.getProperty(HTTP_PROXY_PASSWORD);
                        setProxy(host, port, username, password);
                    }
                }
            }
        } catch (URISyntaxException e) {
            logger.error("Bad service url: " + serviceUrl, e);
        }
    }
}

From source file:de.wikilab.android.friendica01.TwAjax.java

public void updateProxySettings(Context ctx) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    myProxyIp = prefs.getString("proxy_host", null);
    if (myProxyIp == null || myProxyIp.equals("")) {
        myProxyIp = null;/*  w  ww  .j ava2s .  c  o  m*/

        ProxySelector defaultProxySelector = ProxySelector.getDefault();
        List<Proxy> proxyList = defaultProxySelector.select(URI.create("http://frnd.tk"));
        //Log.i("TwAjax", "proxyCount="+proxyList.size()+"|"+((InetSocketAddress)proxyList.get(0).address()).getHostName());
        if (proxyList.size() == 0 || proxyList.get(0).address() == null) {
            return;
        }
        myProxyIp = ((InetSocketAddress) proxyList.get(0).address()).getHostName();
        myProxyPort = ((InetSocketAddress) proxyList.get(0).address()).getPort();
    } else {
        myProxyPort = Integer.valueOf(prefs.getString("proxy_port", null));
    }

    //for(String key:prefs.getAll().keySet()) {
    //Log.w("PREF:",key+"="+prefs.getAll().get(key).toString());   
    //}
    myProxyUsername = prefs.getString("proxy_user", null);
    myProxyPassword = prefs.getString("proxy_password", null);
    Log.i("TwAjax", "PROXY SETTINGS:");
    Log.i("TwAjax", "Host=" + myProxyIp);
    Log.i("TwAjax", "Port=" + myProxyPort);
    Log.i("TwAjax", "User=" + myProxyUsername);

}

From source file:org.mozilla.gecko.updater.UpdateService.java

private URLConnection openConnectionWithProxy(URI uri)
        throws java.net.MalformedURLException, java.io.IOException {
    Log.i(LOGTAG, "opening connection with URI: " + uri);

    ProxySelector ps = ProxySelector.getDefault();
    Proxy proxy = Proxy.NO_PROXY;
    if (ps != null) {
        List<Proxy> proxies = ps.select(uri);
        if (proxies != null && !proxies.isEmpty()) {
            proxy = proxies.get(0);//  w w  w .j  a  va 2 s.co  m
        }
    }

    return uri.toURL().openConnection(proxy);
}

From source file:jp.ne.sakura.kkkon.java.net.socketimpl.testapp.android.SocketImplHookTestApp.java

/** Called when the activity is first created. */
@Override//from w  w w . j a va 2  s  .  co m
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        SocketImplHookFactory.initialize();
    }
    {
        ProxySelector proxySelector = ProxySelector.getDefault();
        Log.d(TAG, "proxySelector=" + proxySelector);
        if (null != proxySelector) {
            URI uri = null;
            try {
                uri = new URI("http://www.google.com/");
            } catch (URISyntaxException e) {
                Log.d(TAG, e.toString());
            }
            List<Proxy> proxies = proxySelector.select(uri);
            if (null != proxies) {
                for (final Proxy proxy : proxies) {
                    Log.d(TAG, " proxy=" + proxy);
                }
            }
        }
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("ExceptionHandler");
    layout.addView(tv);

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    {
        Button btn = new Button(this);
        btn.setText("upload http AsyncTask");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                    @Override
                    protected Boolean doInBackground(String... paramss) {
                        Boolean result = true;
                        Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                        try {
                            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                            Log.d(TAG, "fng=" + Build.FINGERPRINT);
                            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                            HttpPost httpPost = new HttpPost(paramss[0]);
                            //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                            httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                    new Integer(5 * 1000));
                            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                    new Integer(5 * 1000));
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            // <uses-permission android:name="android.permission.INTERNET"/>
                            // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                            HttpResponse response = httpClient.execute(httpPost);
                            Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                        } catch (Exception e) {
                            Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                            result = false;
                        }
                        Log.d(TAG, "upload finish");
                        return result;
                    }

                };

                asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
                asyncTask.isCancelled();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(0.0.0.0)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            destHost = InetAddress.getByName("0.0.0.0");
                            if (null != destHost) {
                                try {
                                    if (destHost.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " reachable");
                                    } else {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " not reachable");
                                    }
                                } catch (IOException e) {

                                }
                            }
                        } catch (UnknownHostException e) {

                        }
                        Log.d(TAG, "destHost=" + destHost);
                    }
                });
                thread.start();
                try {
                    thread.join(1000);
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }
    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(www.google.com)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            InetAddress dest = InetAddress.getByName("www.google.com");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    setContentView(layout);
}

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

public void run() throws SaxonApiException {
    super.run();//from ww  w .j  av a 2 s  .c  o m

    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:org.fuin.esmp.AbstractEventStoreMojo.java

private void addProxySelector(final String proxyHost, final int proxyPort, final String proxyUser,
        final String proxyPassword, final URL downloadUrl) throws URISyntaxException {

    // Add authenticator with proxyUser and proxyPassword
    if (proxyUser != null && proxyPassword != null) {
        Authenticator.setDefault(new Authenticator() {
            @Override// www .j a  va 2  s  .c  om
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }
    final ProxySelector defaultProxySelector = ProxySelector.getDefault();

    final URI downloadUri = downloadUrl.toURI();

    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(final URI uri) {
            if (uri.getHost().equals(downloadUri.getHost()) && proxyHost != null && proxyHost.length() != 0) {
                return singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
            } else {
                return defaultProxySelector.select(uri);
            }
        }

        @Override
        public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) {
        }
    });
}

From source file:com.syncleus.maven.plugins.mongodb.StartMongoMojo.java

private void addProxySelector() {

    // Add authenticator with proxyUser and proxyPassword
    if (proxyUser != null && proxyPassword != null) {
        Authenticator.setDefault(new Authenticator() {
            @Override//from   www.ja  va 2  s  . com
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }

    final ProxySelector defaultProxySelector = ProxySelector.getDefault();
    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(final URI uri) {
            if (uri.getHost().equals("fastdl.mongodb.org")) {
                return singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
            } else {
                return defaultProxySelector.select(uri);
            }
        }

        @Override
        public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) {
        }
    });
}

From source file:org.broad.igv.util.HttpUtils.java

/**
 * Get the system defined proxy defined for the URI, or null if
 * not available. May also return a {@code Proxy} object which
 * represents a direct connection//  w  w w  . ja va  2 s.com
 *
 * @param uri
 * @return
 */
private Proxy getSystemProxy(String uri) {
    try {
        log.debug("Getting system proxy for " + uri);
        ProxySelector selector = ProxySelector.getDefault();
        List<Proxy> proxyList = selector.select(new URI(uri));
        return proxyList.get(0);
    } catch (URISyntaxException e) {
        log.error(e.getMessage(), e);
        return null;
    } catch (NullPointerException e) {
        return null;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return null;
    }

}

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);
    }//from w  ww .  j  a  v a2  s  .  c  o  m

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