Search in sources :

Example 46 with URLConnection

use of java.net.URLConnection in project druid by alibaba.

the class HttpClientUtils method post.

public static boolean post(String serverUrl, String data, long timeout) {
    StringBuilder responseBuilder = null;
    BufferedReader reader = null;
    OutputStreamWriter wr = null;
    URL url;
    try {
        url = new URL(serverUrl);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setConnectTimeout(1000 * 5);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        if (LOG.isDebugEnabled()) {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            responseBuilder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                responseBuilder.append(line).append("\n");
            }
            LOG.debug(responseBuilder.toString());
        }
    } catch (IOException e) {
        LOG.error("", e);
    } finally {
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                LOG.error("close error", e);
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                LOG.error("close error", e);
            }
        }
    }
    return false;
}
Also used : InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) URL(java.net.URL) URLConnection(java.net.URLConnection)

Example 47 with URLConnection

use of java.net.URLConnection in project jmonkeyengine by jMonkeyEngine.

the class NativeLibraryLoader method computeNativesHash.

private static int computeNativesHash() {
    URLConnection conn = null;
    try {
        String classpath = System.getProperty("java.class.path");
        URL url = Thread.currentThread().getContextClassLoader().getResource("com/jme3/system/NativeLibraryLoader.class");
        StringBuilder sb = new StringBuilder(url.toString());
        if (sb.indexOf("jar:") == 0) {
            sb.delete(0, 4);
            sb.delete(sb.indexOf("!"), sb.length());
            sb.delete(sb.lastIndexOf("/") + 1, sb.length());
        }
        try {
            url = new URL(sb.toString());
        } catch (MalformedURLException ex) {
            throw new UnsupportedOperationException(ex);
        }
        conn = url.openConnection();
        int hash = classpath.hashCode() ^ (int) conn.getLastModified();
        return hash;
    } catch (IOException ex) {
        throw new UnsupportedOperationException(ex);
    } finally {
        if (conn != null) {
            try {
                conn.getInputStream().close();
                conn.getOutputStream().close();
            } catch (IOException ex) {
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) URLConnection(java.net.URLConnection) URL(java.net.URL)

Example 48 with URLConnection

use of java.net.URLConnection in project Openfire by igniterealtime.

the class PluginClassLoader method addURLFile.

/**
     * Add the given URL to the classpath for this class loader, 
     * caching the JAR file connection so it can be unloaded later
     * 
     * @param file URL for the JAR file or directory to append to classpath
     */
public void addURLFile(URL file) {
    try {
        // open and cache JAR file connection 
        URLConnection uc = file.openConnection();
        if (uc instanceof JarURLConnection) {
            uc.setUseCaches(true);
            ((JarURLConnection) uc).getManifest();
            cachedJarFiles.add((JarURLConnection) uc);
        }
    } catch (Exception e) {
        Log.warn("Failed to cache plugin JAR file: " + file.toExternalForm());
    }
    addURL(file);
}
Also used : JarURLConnection(java.net.JarURLConnection) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection) MalformedURLException(java.net.MalformedURLException)

Example 49 with URLConnection

use of java.net.URLConnection in project Openfire by igniterealtime.

the class FaviconServlet method getImage.

private byte[] getImage(String url) {
    try {
        // Try to get the fiveicon from the url using an HTTP connection from the pool
        // that also allows to configure timeout values (e.g. connect and get data)
        GetMethod get = new GetMethod(url);
        get.setFollowRedirects(true);
        int response = client.executeMethod(get);
        if (response < 400) {
            // Check that the response was successful. Should we also filter 30* code?
            return get.getResponseBody();
        } else {
            // Remote server returned an error so return null
            return null;
        }
    } catch (IllegalStateException e) {
        // Something failed (probably a method not supported) so try the old stye now
        try {
            URLConnection urlConnection = new URL(url).openConnection();
            urlConnection.setReadTimeout(1000);
            urlConnection.connect();
            try (DataInputStream di = new DataInputStream(urlConnection.getInputStream())) {
                ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
                DataOutputStream out = new DataOutputStream(byteStream);
                int len;
                byte[] b = new byte[1024];
                while ((len = di.read(b)) != -1) {
                    out.write(b, 0, len);
                }
                out.flush();
                return byteStream.toByteArray();
            }
        } catch (IOException ioe) {
            // We failed again so return null
            return null;
        }
    } catch (IOException ioe) {
        // We failed so return null
        return null;
    }
}
Also used : GetMethod(org.apache.commons.httpclient.methods.GetMethod) URL(java.net.URL) URLConnection(java.net.URLConnection)

Example 50 with URLConnection

use of java.net.URLConnection in project hudson-2.x by hudson.

the class ProxyConfiguration method open.

/**
     * This method should be used wherever {@link URL#openConnection()} to internet URLs is invoked directly.
     */
public static URLConnection open(URL url) throws IOException {
    // this code might run on slaves
    Hudson hudson = Hudson.getInstance();
    ProxyConfiguration proxyConfig = hudson != null ? hudson.proxy : null;
    if (proxyConfig == null) {
        return url.openConnection();
    }
    if (proxyConfig.noProxyFor != null) {
        StringTokenizer tokenizer = new StringTokenizer(proxyConfig.noProxyFor, ",");
        while (tokenizer.hasMoreTokens()) {
            String noProxyHost = tokenizer.nextToken().trim();
            if (noProxyHost.contains("*")) {
                if (url.getHost().trim().contains(noProxyHost.replaceAll("\\*", ""))) {
                    return url.openConnection(Proxy.NO_PROXY);
                }
            } else if (url.getHost().trim().equals(noProxyHost)) {
                return url.openConnection(Proxy.NO_PROXY);
            }
        }
    }
    URLConnection urlConnection = url.openConnection(proxyConfig.createProxy());
    if (proxyConfig.isAuthNeeded()) {
        String credentials = proxyConfig.getUserName() + ":" + proxyConfig.getPassword();
        String encoded = new String(Base64.encodeBase64(credentials.getBytes()));
        urlConnection.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
    }
    boolean connected = false;
    int count = 0;
    while (!connected) {
        try {
            urlConnection.connect();
            connected = true;
        } catch (SocketTimeoutException exc) {
            LOGGER.fine("Connection timed out. trying again " + count);
            if (++count > TIME_OUT_RETRY_COUNT) {
                throw new IOException("Could not connect to " + url.toExternalForm() + ". Connection timed out after " + TIME_OUT_RETRY_COUNT + " tries.");
            }
            connected = false;
        } catch (UnknownHostException exc) {
            throw new IOException2("Could not connect to " + url.toExternalForm() + ". Check your internet connection.", exc);
        } catch (ConnectException exc) {
            throw new IOException2("Could not connect to " + url.toExternalForm() + ". Check your internet connection.", exc);
        }
    }
    return urlConnection;
}
Also used : StringTokenizer(java.util.StringTokenizer) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) Hudson(hudson.model.Hudson) IOException(java.io.IOException) URLConnection(java.net.URLConnection) IOException2(hudson.util.IOException2) ConnectException(java.net.ConnectException)

Aggregations

URLConnection (java.net.URLConnection)786 URL (java.net.URL)515 IOException (java.io.IOException)328 HttpURLConnection (java.net.HttpURLConnection)284 InputStream (java.io.InputStream)244 InputStreamReader (java.io.InputStreamReader)148 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)139 Test (org.junit.Test)134 BufferedReader (java.io.BufferedReader)130 MalformedURLException (java.net.MalformedURLException)79 MockResponse (okhttp3.mockwebserver.MockResponse)76 File (java.io.File)73 BufferedInputStream (java.io.BufferedInputStream)55 JarURLConnection (java.net.JarURLConnection)53 OutputStream (java.io.OutputStream)50 FileOutputStream (java.io.FileOutputStream)49 FileInputStream (java.io.FileInputStream)42 GZIPInputStream (java.util.zip.GZIPInputStream)37 ArrayList (java.util.ArrayList)33 URI (java.net.URI)32