Example usage for java.net URLConnection getHeaderFields

List of usage examples for java.net URLConnection getHeaderFields

Introduction

In this page you can find the example usage for java.net URLConnection getHeaderFields.

Prototype

public Map<String, List<String>> getHeaderFields() 

Source Link

Document

Returns an unmodifiable Map of the header fields.

Usage

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

boolean isExpectedRangeMissing(URLConnection conn, Map<String, String> requestProperties) {
    final boolean rangeRequested = (requestProperties != null)
            && (new CI.CIHashMap<String>(requestProperties)).containsKey("Range");
    if (!rangeRequested)
        return false;

    Map<String, List<String>> headerFields = conn.getHeaderFields();
    boolean rangeReceived = (headerFields != null)
            && (new CI.CIHashMap<List<String>>(headerFields)).containsKey("Content-Range");
    return !rangeReceived;
}

From source file:hudson.cli.CLI.java

/**
 * If the server advertises CLI endpoint, returns its location.
 * @deprecated Specific to {@link Mode#REMOTING}.
 *///from w  w  w  . jav  a  2s .c o m
@Deprecated
protected CliPort getCliTcpPort(URL url) throws IOException {
    if (url.getHost() == null || url.getHost().length() == 0) {
        throw new IOException("Invalid URL: " + url);
    }
    URLConnection head = url.openConnection();
    try {
        head.connect();
    } catch (IOException e) {
        throw (IOException) new IOException("Failed to connect to " + url).initCause(e);
    }

    String h = head.getHeaderField("X-Jenkins-CLI-Host");
    if (h == null)
        h = head.getURL().getHost();
    String p1 = head.getHeaderField("X-Jenkins-CLI-Port");
    if (p1 == null)
        p1 = head.getHeaderField("X-Hudson-CLI-Port"); // backward compatibility
    String p2 = head.getHeaderField("X-Jenkins-CLI2-Port");

    String identity = head.getHeaderField("X-Instance-Identity");

    flushURLConnection(head);
    if (p1 == null && p2 == null) {
        verifyJenkinsConnection(head);

        throw new IOException("No X-Jenkins-CLI2-Port among " + head.getHeaderFields().keySet());
    }

    if (p2 != null)
        return new CliPort(new InetSocketAddress(h, Integer.parseInt(p2)), identity, 2);
    else
        return new CliPort(new InetSocketAddress(h, Integer.parseInt(p1)), identity, 1);
}

From source file:io.hummer.util.ws.WebServiceClient.java

private InvocationResult doInvokePOST(Object request, Map<String, String> httpHeaders, int retries)
        throws Exception {
    if (retries < 0)
        throw new Exception("Invocation to " + endpointURL + " failed: " + xmlUtil.toString(request));
    logger.debug("POST request to: " + endpointURL + " with body " + request);
    URL url = new URL(endpointURL);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);/*  ww  w. j  av  a  2  s  . c om*/
    for (String key : httpHeaders.keySet()) {
        conn.setRequestProperty(key, httpHeaders.get(key));
    }
    String theRequest = null;
    if (request instanceof Element) {
        theRequest = xmlUtil.toString((Element) request);
        conn.setRequestProperty("Content-Type", "application/xml");
    } else if (request instanceof String) {
        theRequest = (String) request;
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    }
    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
    theRequest = theRequest.trim();
    w.write(theRequest);
    w.close();
    BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder b = new StringBuilder();
    String temp;
    while ((temp = r.readLine()) != null) {
        b.append(temp);
        b.append("\n");
    }
    String originalResult = b.toString();
    String result = originalResult.trim();
    if (!result.startsWith("<")) // wrap non-xml results (e.g., CSV files)
        result = "<doc>" + result + "</doc>";
    Element resultElement = xmlUtil.toElement(result);
    InvocationResult invResult = new InvocationResult(resultElement, originalResult);
    invResult.getHeaders().putAll(conn.getHeaderFields());
    return invResult;
}

From source file:JNLPAppletLauncher.java

/**
 * Download, cache, verify, and unpack the specified native jar file.
 * Before downloading, check the cached time stamp for the jar file
 * against the server. If the time stamp is valid and matches that of the
 * server, then we will use the locally cached files. This method assumes
 * that cacheDir and nativeTmpDir both exist.
 *
 * An IOException is thrown if the files cannot loaded for some reason.
 *//*from  w w w  . ja  va 2s  .  c om*/
private void processNativeJar(URL url) throws IOException {
    assert cacheDir.isDirectory();
    assert nativeTmpDir.isDirectory();

    // 6618105: Map '\' to '/' prior to stripping off the path
    String urlString = url.toExternalForm().replace('\\', '/');
    String nativeFileName = urlString.substring(urlString.lastIndexOf("/") + 1);
    File nativeFile = new File(cacheDir, nativeFileName);
    // Make sure the file is not "." or ".."
    if (nativeFile.isDirectory()) {
        throw new IOException(nativeFile + " is a directory");
    }

    String tmpStr = nativeFileName;
    int idx = nativeFileName.lastIndexOf(".");
    if (idx > 0) {
        tmpStr = nativeFileName.substring(0, idx);
    }
    String indexFileName = tmpStr + ".idx";
    File indexFile = new File(cacheDir, indexFileName);

    if (VERBOSE) {
        System.err.println("nativeFile = " + nativeFile);
        System.err.println("indexFile = " + indexFile);
    }

    displayMessage("Loading: " + nativeFileName);
    setProgress(0);

    URLConnection conn = url.openConnection();
    conn.connect();

    Map/*<String,List<String>>*/ headerFields = conn.getHeaderFields();
    if (VERBOSE) {
        for (Iterator iter = headerFields.entrySet().iterator(); iter.hasNext();) {
            Entry/*<String,List<String>>*/ e = (Entry) iter.next();
            for (Iterator iter2 = ((List/*<String>*/) e.getValue()).iterator(); iter2.hasNext();) {
                String s = (String) iter2.next();
                if (e.getKey() != null) {
                    System.err.print(e.getKey() + ": ");
                }
                System.err.print(s + " ");
            }
            System.err.println();
        }
        System.err.println();
    }

    // Validate the cache, download the jar if needed
    // TODO: rather than synchronizing on System.out during cache validation,
    // we should use a System property as a lock token (protected by
    // System.out) so we don't hold a synchronized lock on System.out during
    // a potentially long download operation.
    synchronized (System.out) {
        validateCache(conn, nativeFile, indexFile);
    }

    // Unpack the jar file
    displayMessage("Unpacking: " + nativeFileName);
    setProgress(0);

    // Enumerate the jar file looking for native libraries
    JarFile jarFile = new JarFile(nativeFile);
    Set/*<String>*/ rootEntries = getRootEntries(jarFile);
    Set/*<String>*/ nativeLibNames = getNativeLibNames(rootEntries);

    // Validate certificates; throws exception upon validation error
    validateCertificates(jarFile, rootEntries);

    // Extract native libraries from the jar file
    extractNativeLibs(jarFile, rootEntries, nativeLibNames);

    if (VERBOSE) {
        System.err.println();
    }
}

From source file:tufts.vue.URLResource.java

private Properties scrapeHTMLmetaData(URLConnection connection, int maxSearchBytes) throws java.io.IOException {
    Properties metaData = new Properties();

    InputStream byteStream = connection.getInputStream();

    if (DEBUG.DND && DEBUG.META) {
        System.err.println("Getting headers from " + connection);
        System.err.println("Headers: " + connection.getHeaderFields());
    }/*from  www  .j a  v  a  2 s. c om*/

    // note: be sure to call getContentType and don't rely on getting it from the HeaderFields map,
    // as sometimes it's set by the OS for a file:/// URL when there are no header fields (no http server)
    // (actually, this is set by java via a mime type table based on file extension, or a guess based on the stream)
    if (DEBUG.DND)
        System.err.println("*** getting contentType & encoding...");
    final String contentType = connection.getContentType();
    final String contentEncoding = connection.getContentEncoding();
    final int contentLength = connection.getContentLength();

    if (DEBUG.DND)
        System.err.println("*** contentType [" + contentType + "]");
    if (DEBUG.DND)
        System.err.println("*** contentEncoding [" + contentEncoding + "]");
    if (DEBUG.DND)
        System.err.println("*** contentLength [" + contentLength + "]");

    setProperty("url.contentType", contentType);
    setProperty("url.contentEncoding", contentEncoding);
    if (contentLength >= 0)
        setProperty("url.contentLength", contentLength);

    //if (contentType.toLowerCase().startsWith("text/html") == false) {
    if (!isHTML()) { // we only currently handle HTML
        if (DEBUG.Enabled)
            System.err.println("*** contentType [" + contentType + "] not HTML; skipping title extraction");
        return metaData;
    }

    if (DEBUG.DND)
        System.err.println("*** scanning for HTML meta-data...");

    try {
        final BufferedInputStream bufStream = new BufferedInputStream(byteStream, maxSearchBytes);
        bufStream.mark(maxSearchBytes);

        final byte[] byteBuffer = new byte[maxSearchBytes];
        int bytesRead = 0;
        int len = 0;
        // BufferedInputStream still won't read thru a block, so we need to allow
        // a few reads here to get thru a couple of blocks, so we can get up to
        // our maxbytes (e.g., a common return chunk count is 1448 bytes, presumably related to the MTU)
        do {
            int max = maxSearchBytes - bytesRead;
            len = bufStream.read(byteBuffer, bytesRead, max);
            System.out.println("*** read " + len);
            if (len > 0)
                bytesRead += len;
            else if (len < 0)
                break;
        } while (len > 0 && bytesRead < maxSearchBytes);
        if (DEBUG.DND)
            System.out.println("*** Got total chars: " + bytesRead);
        String html = new String(byteBuffer, 0, bytesRead);
        if (DEBUG.DND && DEBUG.META)
            System.out.println("*** HTML-STRING[" + html + "]");

        // first, look for a content encoding, so we can search for and get the title
        // on a properly encoded character stream

        String charset = null;

        Matcher cm = Content_Charset_Regex.matcher(html);
        if (cm.lookingAt()) {
            charset = cm.group(1);
            if (DEBUG.DND)
                System.err.println("*** found HTML specified charset [" + charset + "]");
            setProperty("charset", charset);
        }

        if (charset == null && contentEncoding != null) {
            if (DEBUG.DND || true)
                System.err.println("*** no charset found: using contentEncoding charset " + contentEncoding);
            charset = contentEncoding;
        }

        final String decodedHTML;

        if (charset != null) {
            bufStream.reset();
            InputStreamReader decodedStream = new InputStreamReader(bufStream, charset);
            //InputStreamReader decodedStream = new InputStreamReader(new ByteArrayInputStream(byteBuffer), charset);
            if (true || DEBUG.DND)
                System.out.println("*** decoding bytes into characters with official encoding "
                        + decodedStream.getEncoding());
            setProperty("contentEncoding", decodedStream.getEncoding());
            char[] decoded = new char[bytesRead];
            int decodedChars = decodedStream.read(decoded);
            decodedStream.close();
            if (true || DEBUG.DND)
                System.err.println("*** " + decodedChars + " characters decoded using " + charset);
            decodedHTML = new String(decoded, 0, decodedChars);
        } else
            decodedHTML = html; // we'll just have to go with the default platform charset...

        // these needed to be left open till the decodedStream was done, which
        // although it should never need to read beyond what's already buffered,
        // some internal java code has checks that make sure the underlying stream
        // isn't closed, even it it isn't used.
        byteStream.close();
        bufStream.close();

        Matcher m = HTML_Title_Regex.matcher(decodedHTML);
        if (m.lookingAt()) {
            String title = m.group(1);
            if (true || DEBUG.DND)
                System.err.println("*** found title [" + title + "]");
            metaData.put("title", title.trim());
        }

    } catch (Throwable e) {
        System.err.println("scrapeHTMLmetaData: " + e);
        if (DEBUG.DND)
            e.printStackTrace();
    }

    if (DEBUG.DND || DEBUG.Enabled)
        System.err.println("*** scrapeHTMLmetaData returning [" + metaData + "]");
    return metaData;
}

From source file:com.novartis.opensource.yada.adaptor.RESTAdaptor.java

/**
 * Gets the input stream from the {@link URLConnection} and stores it in 
 * the {@link YADAQueryResult} in {@code yq}
 * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery)
 *///from ww  w. ja va  2  s .  com
@Override
public void execute(YADAQuery yq) throws YADAAdaptorExecutionException {
    boolean isPostPutPatch = this.method.equals(YADARequest.METHOD_POST)
            || this.method.equals(YADARequest.METHOD_PUT) || this.method.equals(YADARequest.METHOD_PATCH);
    resetCountParameter(yq);
    int rows = yq.getData().size() > 0 ? yq.getData().size() : 1;
    /*
     * Remember:
     * A row is an set of YADA URL parameter values, e.g.,
     * 
     *  x,y,z in this:      
     *    ...yada/q/queryname/p/x,y,z
     *  so 1 row
     *    
     *  or each of {col1:x,col2:y,col3:z} and {col1:a,col2:b,col3:c} in this:
     *    ...j=[{qname:queryname,DATA:[{col1:x,col2:y,col3:z},{col1:a,col2:b,col3:c}]}]
     *  so 2 rows
     */
    for (int row = 0; row < rows; row++) {
        String result = "";

        // creates result array and assigns it
        yq.setResult();
        YADAQueryResult yqr = yq.getResult();

        String urlStr = yq.getUrl(row);

        for (int i = 0; i < yq.getParamCount(row); i++) {
            Matcher m = PARAM_URL_RX.matcher(urlStr);
            if (m.matches()) {
                String param = yq.getVals(row).get(i);
                urlStr = urlStr.replaceFirst(PARAM_SYMBOL_RX, m.group(1) + param);
            }
        }

        l.debug("REST url w/params: [" + urlStr + "]");
        try {
            URL url = new URL(urlStr);
            URLConnection conn = null;

            if (this.hasProxy()) {
                String[] proxyStr = this.proxy.split(":");
                Proxy proxySvr = new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(proxyStr[0], Integer.parseInt(proxyStr[1])));
                conn = url.openConnection(proxySvr);
            } else {
                conn = url.openConnection();
            }

            // basic auth
            if (url.getUserInfo() != null) {
                //TODO issue with '@' sign in pw, must decode first
                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
                conn.setRequestProperty("Authorization", basicAuth);
            }

            // cookies
            if (yq.getCookies() != null && yq.getCookies().size() > 0) {
                String cookieStr = "";
                for (HttpCookie cookie : yq.getCookies()) {
                    cookieStr += cookie.getName() + "=" + cookie.getValue() + ";";
                }
                conn.setRequestProperty("Cookie", cookieStr);
            }

            if (yq.getHttpHeaders() != null && yq.getHttpHeaders().length() > 0) {
                l.debug("Processing custom headers...");
                @SuppressWarnings("unchecked")
                Iterator<String> keys = yq.getHttpHeaders().keys();
                while (keys.hasNext()) {
                    String name = keys.next();
                    String value = yq.getHttpHeaders().getString(name);
                    l.debug("Custom header: " + name + " : " + value);
                    conn.setRequestProperty(name, value);
                    if (name.equals(X_HTTP_METHOD_OVERRIDE) && value.equals(YADARequest.METHOD_PATCH)) {
                        l.debug("Resetting method to [" + YADARequest.METHOD_POST + "]");
                        this.method = YADARequest.METHOD_POST;
                    }
                }
            }

            HttpURLConnection hConn = (HttpURLConnection) conn;
            if (!this.method.equals(YADARequest.METHOD_GET)) {
                hConn.setRequestMethod(this.method);
                if (isPostPutPatch) {
                    //TODO make YADA_PAYLOAD case-insensitive and create an alias for it, e.g., ypl
                    // NOTE: YADA_PAYLOAD is a COLUMN NAME found in a JSONParams DATA object.  It 
                    //       is not a YADA param
                    String payload = yq.getDataRow(row).get(YADA_PAYLOAD)[0];
                    hConn.setDoOutput(true);
                    OutputStreamWriter writer;
                    writer = new OutputStreamWriter(conn.getOutputStream());
                    writer.write(payload.toString());
                    writer.flush();
                }
            }

            // debug
            Map<String, List<String>> map = conn.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                l.debug("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
            }

            try (BufferedReader in = new BufferedReader(new InputStreamReader(hConn.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    result += String.format("%1s%n", inputLine);
                }
            }
            yqr.addResult(row, result);
        } catch (MalformedURLException e) {
            String msg = "Unable to access REST source due to a URL issue.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (IOException e) {
            String msg = "Unable to read REST response.";
            throw new YADAAdaptorExecutionException(msg, e);
        }
    }
}

From source file:com.ikanow.infinit.e.harvest.enrichment.custom.UnstructuredAnalysisHarvester.java

public void getRawTextFromUrlIfNeeded(DocumentPojo doc, SourceRssConfigPojo feedConfig) throws IOException {
    if (null != doc.getFullText()) { // Nothing to do
        return;/*from  w ww.j  a v  a2  s . com*/
    }
    Scanner s = null;
    OutputStreamWriter wr = null;
    try {
        URL url = new URL(doc.getUrl());
        URLConnection urlConnect = null;
        String postContent = null;
        if (null != feedConfig) {
            urlConnect = url.openConnection(ProxyManager.getProxy(url, feedConfig.getProxyOverride()));
            if (null != feedConfig.getUserAgent()) {
                urlConnect.setRequestProperty("User-Agent", feedConfig.getUserAgent());
            } // TESTED (by hand)
            if (null != feedConfig.getHttpFields()) {
                for (Map.Entry<String, String> httpFieldPair : feedConfig.getHttpFields().entrySet()) {
                    if (httpFieldPair.getKey().equalsIgnoreCase("content")) {
                        postContent = httpFieldPair.getValue();
                        urlConnect.setDoInput(true);
                        urlConnect.setDoOutput(true);
                    } else {
                        urlConnect.setRequestProperty(httpFieldPair.getKey(), httpFieldPair.getValue());
                    }
                }
            } //TESTED (by hand)
        } else {
            urlConnect = url.openConnection();
        }
        InputStream urlStream = null;
        try {
            securityManager.setSecureFlag(true); // (disallow file/local URL access)
            if (null != postContent) {
                wr = new OutputStreamWriter(urlConnect.getOutputStream());
                wr.write(postContent.toCharArray());
                wr.flush();
            } //TESTED
            urlStream = urlConnect.getInputStream();
        } catch (SecurityException se) {
            throw se;
        } catch (Exception e) { // Try one more time, this time exception out all the way
            securityManager.setSecureFlag(false); // (some file stuff - so need to re-enable)
            if (null != feedConfig) {
                urlConnect = url.openConnection(ProxyManager.getProxy(url, feedConfig.getProxyOverride()));
                if (null != feedConfig.getUserAgent()) {
                    urlConnect.setRequestProperty("User-Agent", feedConfig.getUserAgent());
                } // TESTED
                if (null != feedConfig.getHttpFields()) {
                    for (Map.Entry<String, String> httpFieldPair : feedConfig.getHttpFields().entrySet()) {
                        if (httpFieldPair.getKey().equalsIgnoreCase("content")) {
                            urlConnect.setDoInput(true); // (need to do this again)
                            urlConnect.setDoOutput(true);
                        } else {
                            urlConnect.setRequestProperty(httpFieldPair.getKey(), httpFieldPair.getValue());
                        }
                    }
                } //TESTED
            } else {
                urlConnect = url.openConnection();
            }
            securityManager.setSecureFlag(true); // (disallow file/local URL access)
            if (null != postContent) {
                wr = new OutputStreamWriter(urlConnect.getOutputStream());
                wr.write(postContent.toCharArray());
                wr.flush();
            } //TESTED
            urlStream = urlConnect.getInputStream();
        } finally {
            securityManager.setSecureFlag(false); // (turn security check for local URL/file access off)
        }
        // Grab any interesting header fields
        Map<String, List<String>> headers = urlConnect.getHeaderFields();
        BasicDBObject metadataHeaderObj = null;
        for (Map.Entry<String, List<String>> it : headers.entrySet()) {
            if (null != it.getKey()) {
                if (it.getKey().startsWith("X-") || it.getKey().startsWith("Set-")
                        || it.getKey().startsWith("Location")) {
                    if (null == metadataHeaderObj) {
                        metadataHeaderObj = new BasicDBObject();
                    }
                    metadataHeaderObj.put(it.getKey(), it.getValue());
                }
            }
        } //TESTED
          // Grab the response code
        try {
            HttpURLConnection httpUrlConnect = (HttpURLConnection) urlConnect;
            int responseCode = httpUrlConnect.getResponseCode();
            if (200 != responseCode) {
                if (null == metadataHeaderObj) {
                    metadataHeaderObj = new BasicDBObject();
                }
                metadataHeaderObj.put("responseCode", String.valueOf(responseCode));
            }
        } //TESTED
        catch (Exception e) {
        } // interesting, not an HTTP connect ... shrug and carry on
        if (null != metadataHeaderObj) {
            doc.addToMetadata("__FEED_METADATA__", metadataHeaderObj);
        } //TESTED
        s = new Scanner(urlStream, "UTF-8");
        doc.setFullText(s.useDelimiter("\\A").next());
    } catch (MalformedURLException me) { // This one is worthy of a more useful error message
        throw new MalformedURLException(me.getMessage()
                + ": Likely because the document has no full text (eg JSON) and you are calling a contentMetadata block without setting flags:'m' or 'd'");
    } finally { //(release resources)
        if (null != s) {
            s.close();
        }
        if (null != wr) {
            wr.close();
        }
    }

}

From source file:org.orbeon.oxf.util.Connection.java

/**
 * Open the connection. This sends request headers, request body, and reads status and response headers.
 *
 * @return                  connection result
 *///  w  ww.j  av  a 2s  .c o m
public ConnectionResult connect() {

    final boolean isDebugEnabled = indentedLogger.isDebugEnabled();

    // Perform connection
    final String scheme = connectionURL.getProtocol();
    if (isHTTPOrHTTPS(scheme)
            || (httpMethod.equals("GET") && (scheme.equals("file") || scheme.equals("oxf")))) {
        // http MUST be supported
        // https SHOULD be supported
        // file SHOULD be supported
        try {
            // Create URL connection object
            final URLConnection urlConnection = connectionURL.openConnection();
            final HTTPURLConnection httpURLConnection = (urlConnection instanceof HTTPURLConnection)
                    ? (HTTPURLConnection) urlConnection
                    : null;

            // Whether a message body must be sent
            final boolean hasRequestBody = httpMethod.equals("POST") || httpMethod.equals("PUT");

            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(hasRequestBody);

            // Configure HTTPURLConnection
            if (httpURLConnection != null) {
                // Set state if possible
                httpURLConnection.setCookieStore(this.cookieStore);

                // Set method
                httpURLConnection.setRequestMethod(httpMethod);

                // Set credentials
                if (credentials != null) {

                    httpURLConnection.setUsername(credentials.username);
                    if (credentials.password != null)
                        httpURLConnection.setPassword(credentials.password);
                    if (credentials.preemptiveAuthentication != null)
                        httpURLConnection.setPreemptiveAuthentication(credentials.preemptiveAuthentication);
                    if (credentials.domain != null)
                        httpURLConnection.setDomain(credentials.domain);
                }
            }

            // Update request headers
            {
                // Handle SOAP
                // Set request Content-Type, SOAPAction or Accept header if needed
                final boolean didSOAP = handleSOAP(indentedLogger, httpMethod, headersMap, contentType,
                        hasRequestBody);

                // Set request content type
                if (!didSOAP && hasRequestBody) {
                    final String actualContentType = (contentType != null) ? contentType : "application/xml";
                    headersMap.put("Content-Type", new String[] { actualContentType });
                    indentedLogger.logDebug(LOG_TYPE, "setting header", "Content-Type", actualContentType);
                }
            }

            // Set headers on connection
            final List<String> headersToLog;
            if (headersMap != null && headersMap.size() > 0) {

                headersToLog = isDebugEnabled ? new ArrayList<String>() : null;

                for (Map.Entry<String, String[]> currentEntry : headersMap.entrySet()) {
                    final String currentHeaderName = currentEntry.getKey();
                    final String[] currentHeaderValues = currentEntry.getValue();
                    if (currentHeaderValues != null) {
                        // Add all header values as "request properties"
                        for (String currentHeaderValue : currentHeaderValues) {
                            urlConnection.addRequestProperty(currentHeaderName, currentHeaderValue);

                            if (headersToLog != null) {
                                headersToLog.add(currentHeaderName);
                                headersToLog.add(currentHeaderValue);
                            }
                        }
                    }
                }
            } else {
                headersToLog = null;
            }

            // Log request details except body
            if (isDebugEnabled) {
                // Basic connection information
                final URI connectionURI;
                try {
                    String userInfo = connectionURL.getUserInfo();
                    if (userInfo != null) {
                        final int colonIndex = userInfo.indexOf(':');
                        if (colonIndex != -1)
                            userInfo = userInfo.substring(0, colonIndex + 1) + "xxxxxxxx";// hide password in logs
                    }
                    connectionURI = new URI(connectionURL.getProtocol(), userInfo, connectionURL.getHost(),
                            connectionURL.getPort(), connectionURL.getPath(), connectionURL.getQuery(),
                            connectionURL.getRef());
                } catch (URISyntaxException e) {
                    throw new OXFException(e);
                }
                indentedLogger.logDebug(LOG_TYPE, "opening URL connection", "method", httpMethod, "URL",
                        connectionURI.toString(), "request Content-Type", contentType);

                // Log all headers
                if (headersToLog != null) {
                    final String[] strings = new String[headersToLog.size()];
                    indentedLogger.logDebug(LOG_TYPE, "request headers", headersToLog.toArray(strings));
                }
            }

            // Write request body if needed
            if (hasRequestBody) {

                // Case of empty body
                if (messageBody == null)
                    messageBody = new byte[0];

                // Log message body for debugging purposes
                if (logBody)
                    logRequestBody(indentedLogger, contentType, messageBody);

                // Set request body on connection
                httpURLConnection.setRequestBody(messageBody);
            }

            // Connect
            urlConnection.connect();

            if (httpURLConnection != null) {
                // Get state if possible
                // This is either the state we set above before calling connect(), or a new state if we didn't provide any
                this.cookieStore = httpURLConnection.getCookieStore();
            }

            // Create result
            final ConnectionResult connectionResult = new ConnectionResult(connectionURL.toExternalForm()) {
                @Override
                public void close() {
                    if (getResponseInputStream() != null) {
                        try {
                            getResponseInputStream().close();
                        } catch (IOException e) {
                            throw new OXFException(
                                    "Exception while closing input stream for action: " + connectionURL);
                        }
                    }

                    if (httpURLConnection != null)
                        httpURLConnection.disconnect();
                }
            };

            // Get response information that needs to be forwarded
            {
                // Status code
                connectionResult.statusCode = (httpURLConnection != null) ? httpURLConnection.getResponseCode()
                        : 200;

                // Headers
                connectionResult.responseHeaders = urlConnection.getHeaderFields();
                connectionResult.setLastModified(NetUtils.getLastModifiedAsLong(urlConnection));

                // Content-Type
                connectionResult.setResponseContentType(urlConnection.getContentType(), "application/xml");
            }

            // Log response details except body
            if (isDebugEnabled) {
                connectionResult.logResponseDetailsIfNeeded(indentedLogger, Level.DEBUG, LOG_TYPE);
            }

            // Response stream
            connectionResult.setResponseInputStream(urlConnection.getInputStream());

            // Log response body
            if (isDebugEnabled) {
                connectionResult.logResponseBody(indentedLogger, Level.DEBUG, LOG_TYPE, logBody);
            }

            return connectionResult;

        } catch (IOException e) {
            throw new ValidationException(e, new LocationData(connectionURL.toExternalForm(), -1, -1));
        }
    } else if (!httpMethod.equals("GET") && (scheme.equals("file") || scheme.equals("oxf"))) {
        // TODO: implement writing to file: and oxf:
        // SHOULD be supported (should probably support oxf: as well)
        throw new OXFException("submission URL scheme not yet implemented: " + scheme);
    } else if (scheme.equals("mailto")) {
        // TODO: implement sending mail
        // MAY be supported
        throw new OXFException("submission URL scheme not yet implemented: " + scheme);
    } else {
        throw new OXFException("submission URL scheme not supported: " + scheme);
    }
}