Example usage for java.net HttpURLConnection setDefaultUseCaches

List of usage examples for java.net HttpURLConnection setDefaultUseCaches

Introduction

In this page you can find the example usage for java.net HttpURLConnection setDefaultUseCaches.

Prototype

public void setDefaultUseCaches(boolean defaultusecaches) 

Source Link

Document

Sets the default value of the useCaches field to the specified value.

Usage

From source file:com.googlecode.jsonrpc4j.JsonRpcHttpClient.java

/**
 * Prepares a connection to the server.//from   w w  w  .j  a v a  2  s .c o m
 * @param extraHeaders extra headers to add to the request
 * @return the unopened connection
 * @throws IOException
 */
protected HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {

    // create URLConnection
    HttpURLConnection con = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
    con.setConnectTimeout(connectionTimeoutMillis);
    con.setReadTimeout(readTimeoutMillis);
    con.setAllowUserInteraction(false);
    con.setDefaultUseCaches(false);
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setInstanceFollowRedirects(true);
    con.setRequestMethod("POST");

    // do stuff for ssl
    if (HttpsURLConnection.class.isInstance(con)) {
        HttpsURLConnection https = HttpsURLConnection.class.cast(con);
        if (hostNameVerifier != null) {
            https.setHostnameVerifier(hostNameVerifier);
        }
        if (sslContext != null) {
            https.setSSLSocketFactory(sslContext.getSocketFactory());
        }
    }

    // add headers
    con.setRequestProperty("Content-Type", "application/json-rpc");
    for (Entry<String, String> entry : headers.entrySet()) {
        con.setRequestProperty(entry.getKey(), entry.getValue());
    }
    for (Entry<String, String> entry : extraHeaders.entrySet()) {
        con.setRequestProperty(entry.getKey(), entry.getValue());
    }

    // return it
    return con;
}

From source file:petascope.wcps.server.test.FullTestsOnline.java

/**
 * Send an request to the WCPS server./*from  ww w . j  av a2  s  . co  m*/
 * Returns a message on error and null otherwise.
 */
public String runOneTest(String param, String query, String method) throws MalformedURLException, IOException {
    //      System.out.println("--------------------");
    //      System.out.println(query);
    //      System.out.println("\t--------------------");

    // connect to the servlet
    URL servlet = new URL(PetascopeURL);
    HttpURLConnection conn = (HttpURLConnection) servlet.openConnection();

    // inform the connection that we will send output and accept input
    conn.setDoInput(true);
    conn.setDoOutput(true);

    // Don't use a cached version of URL connection.
    conn.setUseCaches(false);
    conn.setDefaultUseCaches(false);

    // Default method is GET
    if (method.equals("POST")) {
        conn.setRequestMethod(method);
    }

    // For POST: We send binary data
    if (method.equals("POST")) {
        //            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        //            query = URLEncoder.encode(query, "UTF-8");
    }

    if (param.equals("") == false) {
        param += "=";
    }

    String data = param + query;
    DataOutputStream out = new DataOutputStream(conn.getOutputStream());

    out.writeBytes(data);
    out.flush();
    out.close();

    BufferedReader cgiOutput = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line1 = cgiOutput.readLine();
    String line2 = cgiOutput.readLine();
    String line3 = cgiOutput.readLine();

    System.out.println("\t" + line1);
    System.out.println("\t" + line2);
    System.out.println("\t" + line3);

    if ((line1 != null) && (line2 != null) && (line3 != null)) {
        StringBuffer output = new StringBuffer(line1 + line2 + line3);
        while (cgiOutput.ready()) {
            output.append(cgiOutput.readLine());
        }

        // Try to parse error message
        if (line1.startsWith("<")) {
            DocumentBuilder builder = null;
            try {
                DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
                domFactory.setNamespaceAware(true); // never forget this!
                builder = domFactory.newDocumentBuilder();
                Document doc = builder.parse(IOUtils.toInputStream(output.toString()));
                Element rootElem = doc.getDocumentElement();
                if (rootElem.getNodeName().endsWith("ExceptionReport")) {
                    return output.toString();
                }
            } catch (Exception e) {
            }
        }

    }

    return null;
}

From source file:com.streamsets.datacollector.restapi.TestRestApiAuthorization.java

private void test(List<RestApi> apis, boolean authzEnabled) throws Exception {
    String baseUrl = startServer(authzEnabled);
    try {//from  w  w w . ja  va  2 s. c  o m
        for (RestApi api : apis) {
            Set<String> has = api.roles;
            for (String user : ALL_ROLES) {
                user = "guest";
                URL url = new URL(baseUrl + api.uriPath);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty(CsrfProtectionFilter.HEADER_NAME, "CSRF");
                if (authzEnabled) {
                    conn.setRequestProperty("Authorization",
                            "Basic " + Base64.encodeBase64URLSafeString((user + ":" + user).getBytes()));
                }
                conn.setRequestMethod(api.method.name());
                conn.setDefaultUseCaches(false);
                if (authzEnabled) {
                    if (has.contains(user)) {
                        Assert.assertNotEquals(
                                Utils.format("Authz '{}' User '{}' METHOD '{}' API '{}'", authzEnabled, user,
                                        api.method, api.uriPath),
                                HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
                    } else {
                        Assert.assertEquals(
                                Utils.format("Authz '{}' User '{}' METHOD '{}' API '{}'", authzEnabled, user,
                                        api.method, api.uriPath),
                                HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
                    }
                } else {
                    Assert.assertNotEquals(
                            Utils.format("Authz '{}' User '{}' METHOD '{}' API '{}'", authzEnabled, user,
                                    api.method, api.uriPath),
                            HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
                }
            }
        }
    } finally {
        stopServer();
    }
}

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

/**
 * The "real" connection method//from   w w  w  .j a va2s  .co  m
 *
 * @param url
 * @param requestProperties
 * @param method
 * @return
 * @throws java.io.IOException
 */
private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties, String method,
        int redirectCount) throws IOException {

    //Encode query string portions
    url = StringUtils.encodeURLQueryString(url);
    if (log.isTraceEnabled()) {
        log.trace(url);
    }

    //Encode base portions. Right now just spaces, most common case
    //TODO This is a hack and doesn't work for all characters which need it
    if (StringUtils.countChar(url.toExternalForm(), ' ') > 0) {
        String newPath = url.toExternalForm().replaceAll(" ", "%20");
        url = new URL(newPath);
    }

    Proxy sysProxy = null;
    boolean igvProxySettingsExist = proxySettings != null && proxySettings.useProxy;
    //Only check for system proxy if igv proxy settings not found
    if (!igvProxySettingsExist) {
        sysProxy = getSystemProxy(url.toExternalForm());
    }
    boolean useProxy = sysProxy != null || igvProxySettingsExist;

    HttpURLConnection conn;
    if (useProxy) {
        Proxy proxy = sysProxy;
        if (igvProxySettingsExist) {
            if (proxySettings.type == Proxy.Type.DIRECT) {
                proxy = Proxy.NO_PROXY;
            } else {
                proxy = new Proxy(proxySettings.type,
                        new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort));
            }
        }
        conn = (HttpURLConnection) url.openConnection(proxy);

        if (igvProxySettingsExist && proxySettings.auth && proxySettings.user != null
                && proxySettings.pw != null) {
            byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes();

            String encodedUserPwd = String.valueOf(Base64Coder.encode(bytes));
            conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
        }
    } else {
        conn = (HttpURLConnection) url.openConnection();
    }

    if (GSUtils.isGenomeSpace(url)) {
        conn.setRequestProperty("Accept", "application/json,text/plain");
    } else {
        conn.setRequestProperty("Accept", "text/plain");
    }

    //------//
    //There seems to be a bug with JWS caches
    //So we avoid caching

    //This default is persistent, really should be available statically but isn't
    conn.setDefaultUseCaches(false);
    conn.setUseCaches(false);
    //------//

    conn.setConnectTimeout(Globals.CONNECT_TIMEOUT);
    conn.setReadTimeout(Globals.READ_TIMEOUT);
    conn.setRequestMethod(method);
    conn.setRequestProperty("Connection", "Keep-Alive");
    if (requestProperties != null) {
        for (Map.Entry<String, String> prop : requestProperties.entrySet()) {
            conn.setRequestProperty(prop.getKey(), prop.getValue());
        }
    }
    conn.setRequestProperty("User-Agent", Globals.applicationString());

    if (method.equals("PUT")) {
        return conn;
    } else {

        int code = conn.getResponseCode();

        if (log.isDebugEnabled()) {
            //logHeaders(conn);
        }

        // Redirects.  These can occur even if followRedirects == true if there is a change in protocol,
        // for example http -> https.
        if (code >= 300 && code < 400) {

            if (redirectCount > MAX_REDIRECTS) {
                throw new IOException("Too many redirects");
            }

            String newLocation = conn.getHeaderField("Location");
            log.debug("Redirecting to " + newLocation);

            return openConnection(new URL(newLocation), requestProperties, method, redirectCount++);
        }

        // TODO -- handle other response codes.
        else if (code >= 400) {

            String message;
            if (code == 404) {
                message = "File not found: " + url.toString();
                throw new FileNotFoundException(message);
            } else if (code == 401) {
                // Looks like this only happens when user hits "Cancel".
                // message = "Not authorized to view this file";
                // JOptionPane.showMessageDialog(null, message, "HTTP error", JOptionPane.ERROR_MESSAGE);
                redirectCount = MAX_REDIRECTS + 1;
                return null;
            } else {
                message = conn.getResponseMessage();
            }
            String details = readErrorStream(conn);
            log.error("URL: " + url.toExternalForm() + ". error stream: " + details);
            log.error("Code: " + code + ". " + message);
            HttpResponseException exc = new HttpResponseException(code);
            throw exc;
        }
    }
    return conn;
}

From source file:fur.shadowdrake.minecraft.InstallPanel.java

public boolean downloadMojangLauncher() {
    URL u;/*from ww w.j  a  va 2s.  c o m*/
    HttpURLConnection connection;
    Proxy p;
    InputStream is;
    FileOutputStream fos;

    if (new File(config.getInstallDir(), "Minecraft.jar").isFile()) {
        return true;
    }

    log.println("Connecting to Mojang server...");
    if (config.getHttpProxy().isEmpty()) {
        p = Proxy.NO_PROXY;
    } else {
        Authenticator.setDefault(new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                if (getRequestorType() == Authenticator.RequestorType.PROXY) {
                    return config.getHttpProxyCredentials();
                } else {
                    return super.getPasswordAuthentication();
                }
            }
        });
        p = new Proxy(Proxy.Type.HTTP, new ProxyAddress(config.getHttpProxy(), 3128).getSockaddr());
    }
    try {
        u = new URL("https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.jar");
        connection = (HttpURLConnection) u.openConnection(p);
        connection.addRequestProperty("User-agent", "Minecraft Bootloader");
        connection.setUseCaches(false);
        connection.setDefaultUseCaches(false);
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.connect();
        log.println("Mojang server returned " + connection.getResponseMessage());
        if (connection.getResponseCode() != 200) {
            connection.disconnect();
            return false;
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (IOException ex) {
        Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex);
        log.println("Connection to Mojang server failed.");
        return false;
    }

    try {
        is = connection.getInputStream();
        fos = new FileOutputStream(new File(config.getInstallDir(), "Minecraft.jar"));
        log.println("Downloading Minecraft.jar");
        byte[] buffer = new byte[4096];
        for (int n = is.read(buffer); n > 0; n = is.read(buffer)) {
            fos.write(buffer, 0, n);
        }
        fos.close();
        is.close();
        connection.disconnect();
        log.println("Done.");
    } catch (IOException ex) {
        Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, "downloadMojangLauncher", ex);
        log.println("Faild to save file.");
        return false;
    }
    return true;
}

From source file:com.codename1.impl.android.AndroidImplementation.java

public Object connect(String url, boolean read, boolean write, int timeout) throws IOException {
    URL u = new URL(url);
    CookieHandler.setDefault(null);
    URLConnection con = u.openConnection();
    if (con instanceof HttpURLConnection) {
        HttpURLConnection c = (HttpURLConnection) con;
        c.setUseCaches(false);//from   www .ja  v  a  2 s  .  com
        c.setDefaultUseCaches(false);
        c.setInstanceFollowRedirects(false);
        if (timeout > -1) {
            c.setConnectTimeout(timeout);
        }
        if (read) {
            if (timeout > -1) {
                c.setReadTimeout(timeout);
            } else {
                c.setReadTimeout(10000);
            }
        }
        if (android.os.Build.VERSION.SDK_INT > 13) {
            c.setRequestProperty("Connection", "close");
        }
    }
    con.setDoInput(read);
    con.setDoOutput(write);
    return con;
}