Example usage for java.net HttpURLConnection setUseCaches

List of usage examples for java.net HttpURLConnection setUseCaches

Introduction

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

Prototype

public void setUseCaches(boolean usecaches) 

Source Link

Document

Sets the value of the useCaches field of this URLConnection to the specified value.

Usage

From source file:ccs_server.Sender.java

/**
 * Makes an HTTP POST request to a given endpoint.
 *
 * <p>//ww  w  . j  a  va 2  s. co  m
 * <strong>Note: </strong> the returned connected should not be disconnected,
 * otherwise it would kill persistent connections made using Keep-Alive.
 *
 * @param url endpoint to post the request.
 * @param contentType type of request.
 * @param body body of the request.
 *
 * @return the underlying connection.
 *
 * @throws IOException propagated from underlying methods.
 */
protected HttpURLConnection post(String url, String contentType, String body) throws IOException {
    if (url == null || body == null) {
        throw new IllegalArgumentException("arguments cannot be null");
    }
    if (!url.startsWith("https://")) {
        logger.warning("URL does not use https: " + url);
    }
    logger.fine("Sending POST to " + url);
    logger.finest("POST body: " + body);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = getConnection(url);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", contentType);
    conn.setRequestProperty("Authorization", "key=" + key);
    OutputStream out = conn.getOutputStream();
    try {
        out.write(bytes);
    } finally {
        close(out);
    }
    return conn;
}

From source file:org.bsc.confluence.xmlrpc.XMLRPCApp.java

/**
 * /*  w ww  .  j ava  2s  . c om*/
 * @throws Exception 
 */
protected void usingHttp() throws Exception {

    ConfluenceProxy proxyInfo = null;

    final ConfluenceService.Credentials credentials = new ConfluenceService.Credentials(username /*args[1]*/,
            password/*args[2]*/);

    final SSLCertificateInfo sslInfo = new SSLCertificateInfo();

    final XMLRPCConfluenceServiceImpl confluence = XMLRPCConfluenceServiceImpl.createInstanceDetectingVersion(
            ConfluenceService.Protocol.XMLRPC.addTo(url), //args[0],
            credentials, proxyInfo, sslInfo);

    confluence.getPage("CIRC", "Best Movies").thenAccept(p -> {

        Model.Page page = p.orElseThrow(() -> new RuntimeException("page not found!"));

        java.io.InputStream is = null;
        java.io.FileOutputStream fos = null;
        try {

            final String req = String.format("%s/%s?pageId=%s", url, ExportFormat.PDF.url, page.getId());
            System.out.println(req);
            java.net.URL _url = new java.net.URL(req);

            HttpURLConnection urlConnection = (HttpURLConnection) _url.openConnection();
            //HttpURLConnection.setFollowRedirects(true);
            //urlConnection.setInstanceFollowRedirects(true);
            String userpass = username + ":" + password;

            String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
            urlConnection.addRequestProperty("Authorization", basicAuth);
            urlConnection.addRequestProperty("X-Atlassian-Token", "no-check");
            urlConnection.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");

            urlConnection.setUseCaches(false);

            is = urlConnection.getInputStream();

            fos = new java.io.FileOutputStream("target/out.pdf");

            IOUtils.copy(is, fos);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fos);
        }

    });

}

From source file:com.aptana.jira.core.JiraManager.java

@SuppressWarnings("restriction")
protected HttpURLConnection createConnection(String urlString, String username, String password)
        throws MalformedURLException, IOException {
    HttpURLConnection connection;
    URL url = new URL(urlString);
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(USER_AGENT, getProjectVersion());
    connection.setRequestProperty(ACCEPT_HEADER, ACCEPT_CONTENT_TYPES);
    connection.setRequestProperty(CONTENT_TYPE, ACCEPT_CONTENT_TYPES);
    connection.setUseCaches(false);//  w w  w.j  a v  a  2  s  .c  om
    connection.setAllowUserInteraction(false);
    String usernamePassword = username + ":" + password; //$NON-NLS-1$
    connection.setRequestProperty(AUTHORIZATION_HEADER,
            "Basic " + new String(Base64.encode(usernamePassword.getBytes()))); //$NON-NLS-1$
    return connection;
}

From source file:jackwu.com.gasprice.GCMService.RegistrationIntentService.java

/**
 * Persist registration to third-party servers.
 *
 * Modify this method to associate the user's GCM registration token with any server-side account
 * maintained by your application./* w  ww  .jav  a 2  s  . c om*/
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token, String device_id) throws Exception {
    // Add custom implementation, as needed.
    HttpURLConnection urlConnection = null;
    URL url = null;
    String parameter = "device_id=" + device_id;
    String parameter2 = "gcm_regid=" + token;
    try {
        url = new URL(getString(R.string.server_address_register));
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/x-www.form-urlencoded");
        urlConnection.setRequestProperty("Content-Language", "en-US");
        urlConnection.setUseCaches(false);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
        dos.writeBytes(parameter);
        dos.writeBytes(parameter2);
        dos.flush();
        dos.close();

        int responseCode = urlConnection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            if (!response.toString().equals("success")) {
                throw new Exception("not success");
            }
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.langerhans.wallet.ui.send.RequestWalletBalanceTask.java

public void requestWalletBalance(final Address address) {
    backgroundHandler.post(new Runnable() {
        @Override//from  ww  w  .  ja va  2  s  . co  m
        public void run() {
            // Use either dogechain or chain.so
            List<String> urls = new ArrayList<String>(2);
            urls.add(Constants.DOGECHAIN_API_URL);
            urls.add(Constants.CHAINSO_API_URL);
            Collections.shuffle(urls, new Random(System.nanoTime()));

            final StringBuilder url = new StringBuilder(urls.get(0));
            url.append(address.toString());

            log.debug("trying to request wallet balance from {}", url);

            HttpURLConnection connection = null;
            Reader reader = null;

            try {
                connection = (HttpURLConnection) new URL(url.toString()).openConnection();

                connection.setInstanceFollowRedirects(false);
                connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);

                connection.setRequestMethod("GET");
                if (userAgent != null)
                    connection.addRequestProperty("User-Agent", userAgent);
                connection.connect();

                final int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                            Charsets.UTF_8);
                    final StringBuilder content = new StringBuilder();
                    Io.copy(reader, content);

                    final JSONObject json = new JSONObject(content.toString());

                    final int success = json.getInt("success");
                    if (success != 1)
                        throw new IOException("api status " + success + " when fetching unspent outputs");

                    final JSONArray jsonOutputs = json.getJSONArray("unspent_outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("tx_hash"));
                        final int uxtoIndex = jsonOutput.getInt("tx_output_n");
                        final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script"));
                        final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value")));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        if (tx.getOutputs().size() > uxtoIndex)
                            throw new IllegalStateException("cannot reach index " + uxtoIndex
                                    + ", tx already has " + tx.getOutputs().size() + " outputs");

                        // fill with dummies
                        while (tx.getOutputs().size() < uxtoIndex)
                            tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                    Coin.NEGATIVE_SATOSHI, new byte[] {}));

                        // add the real output
                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                uxtoValue, uxtoScriptBytes);
                        tx.addOutput(output);
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final String responseMessage = connection.getResponseMessage();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);

                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException x) {
                        // swallow
                    }
                }

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

From source file:ja.ohac.wallet.ui.send.RequestWalletBalanceTask.java

public void requestWalletBalance(final Address... addresses) {
    backgroundHandler.post(new Runnable() {
        @Override/*from w  w w  .j av  a  2s.  c  o  m*/
        public void run() {
            final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL);
            url.append("unspent-outputs");
            url.append("?per_page=MAX");
            for (final Address address : addresses)
                url.append("&address[]=").append(address.toString());

            log.debug("trying to request wallet balance from {}", url);

            HttpURLConnection connection = null;
            Reader reader = null;

            try {
                connection = (HttpURLConnection) new URL(url.toString()).openConnection();

                connection.setInstanceFollowRedirects(false);
                connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);

                connection.setRequestMethod("GET");
                if (userAgent != null)
                    connection.addRequestProperty("User-Agent", userAgent);
                connection.connect();

                final int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                            Charsets.UTF_8);
                    final StringBuilder content = new StringBuilder();
                    Io.copy(reader, content);

                    final JSONObject json = new JSONObject(content.toString());

                    final int status = json.getInt("status");
                    if (status != 200)
                        throw new IOException("api status " + status + " when fetching unspent outputs");

                    final JSONObject jsonData = json.getJSONObject("data");

                    final JSONObject jsonPagination = jsonData.getJSONObject("pagination");

                    if (!"false".equals(jsonPagination.getString("next_page")))
                        throw new IllegalStateException("result set too big");

                    final JSONArray jsonOutputs = jsonData.getJSONArray("outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        if (jsonOutput.getInt("is_spent") != 0)
                            throw new IllegalStateException("UXTO not spent");

                        final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash"));
                        final int uxtoIndex = jsonOutput.getInt("transaction_index");
                        final byte[] uxtoScriptBytes = BaseEncoding.base16().lowerCase()
                                .decode(jsonOutput.getString("script_pub_key"));
                        final BigInteger uxtoValue = new BigInteger(jsonOutput.getString("value"));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        if (tx.getOutputs().size() > uxtoIndex)
                            throw new IllegalStateException("cannot reach index " + uxtoIndex
                                    + ", tx already has " + tx.getOutputs().size() + " outputs");

                        // fill with dummies
                        while (tx.getOutputs().size() < uxtoIndex)
                            tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                    Coin.NEGATIVE_SATOSHI, new byte[] {}));

                        // add the real output
                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                Coin.valueOf(uxtoValue.longValue()), uxtoScriptBytes);
                        tx.addOutput(output);
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final String responseMessage = connection.getResponseMessage();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);

                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException x) {
                        // swallow
                    }
                }

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

From source file:de.schildbach.wallet.ui.send.RequestWalletBalanceTask.java

public void requestWalletBalance(final Address... addresses) {
    backgroundHandler.post(new Runnable() {
        @Override/*from  www  .j a  v a  2s . c om*/
        public void run() {
            final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL);
            url.append("unspent-outputs");
            url.append("?per_page=MAX");
            for (final Address address : addresses)
                url.append("&address[]=").append(address.toString());

            log.debug("trying to request wallet balance from {}", url);

            HttpURLConnection connection = null;
            Reader reader = null;

            try {
                connection = (HttpURLConnection) new URL(url.toString()).openConnection();

                connection.setInstanceFollowRedirects(false);
                connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);

                connection.setRequestMethod("GET");
                if (userAgent != null)
                    connection.addRequestProperty("User-Agent", userAgent);
                connection.connect();

                final int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                            Charsets.UTF_8);
                    final StringBuilder content = new StringBuilder();
                    Io.copy(reader, content);

                    final JSONObject json = new JSONObject(content.toString());

                    final int status = json.getInt("status");
                    if (status != 200)
                        throw new IOException("api status " + status + " when fetching unspent outputs");

                    final JSONObject jsonData = json.getJSONObject("data");

                    final JSONObject jsonPagination = jsonData.getJSONObject("pagination");

                    if (!"false".equals(jsonPagination.getString("next_page")))
                        throw new IllegalStateException("result set too big");

                    final JSONArray jsonOutputs = jsonData.getJSONArray("outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        if (jsonOutput.getInt("is_spent") != 0)
                            throw new IllegalStateException("UXTO not spent");

                        final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash"));
                        final int uxtoIndex = jsonOutput.getInt("transaction_index");
                        final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script_pub_key"));
                        final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value")));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        if (tx.getOutputs().size() > uxtoIndex)
                            throw new IllegalStateException("cannot reach index " + uxtoIndex
                                    + ", tx already has " + tx.getOutputs().size() + " outputs");

                        // fill with dummies
                        while (tx.getOutputs().size() < uxtoIndex)
                            tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                    Coin.NEGATIVE_SATOSHI, new byte[] {}));

                        // add the real output
                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                uxtoValue, uxtoScriptBytes);
                        tx.addOutput(output);
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final String responseMessage = connection.getResponseMessage();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);

                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException x) {
                        // swallow
                    }
                }

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

From source file:net.technicpack.launchercore.mirror.MirrorStore.java

public String getETag(String address) {
    String md5 = "";

    try {/*from   w w w  .j  a  va2s .com*/
        URL url = getFullUrl(address);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);

        String eTag = conn.getHeaderField("ETag");
        if (eTag != null) {
            eTag = eTag.replaceAll("^\"|\"$", "");
            if (eTag.length() == 32) {
                md5 = eTag;
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return md5;
}

From source file:edu.pdx.cecs.orcycle.UserInfoUploader.java

boolean uploadUserInfoV4() {
    boolean result = false;
    final String postUrl = mCtx.getResources().getString(R.string.post_url);

    try {//from  ww w  .j  av a  2 s .  c o  m
        JSONArray userResponses = getUserResponsesJSON();

        URL url = new URL(postUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Cycleatl-Protocol-Version", "4");

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        JSONObject jsonUser;
        if (null != (jsonUser = getUserJSON())) {
            try {
                String deviceId = userId;

                dos.writeBytes(fieldSep + ContentField("user") + jsonUser.toString() + "\r\n");
                dos.writeBytes(
                        fieldSep + ContentField("version") + String.valueOf(kSaveProtocolVersion4) + "\r\n");
                dos.writeBytes(fieldSep + ContentField("device") + deviceId + "\r\n");
                dos.writeBytes(fieldSep + ContentField("userResponses") + userResponses.toString() + "\r\n");
                dos.writeBytes(fieldSep);
                dos.flush();
            } catch (Exception ex) {
                Log.e(MODULE_TAG, ex.getMessage());
                return false;
            } finally {
                dos.close();
            }
            int serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();
            // JSONObject responseData = new JSONObject(serverResponseMessage);
            Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
            if (serverResponseCode == 201 || serverResponseCode == 202) {
                // TODO: Record somehow that data was uploaded successfully
                result = true;
            }
        } else {
            result = false;
        }
    } catch (IllegalStateException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }
    return result;
}

From source file:com.zhonghui.tool.controller.HttpClient.java

/**
 * get/*  w  w  w  .ja v  a2s  .c o m*/
 *
 * @return
 * @throws ProtocolException
 */
private HttpURLConnection createConnectionGet(String encoding) throws ProtocolException {
    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    httpURLConnection.setConnectTimeout(this.connectionTimeout);// 
    httpURLConnection.setReadTimeout(this.readTimeOut);// ?
    httpURLConnection.setUseCaches(false);// ?
    httpURLConnection.setRequestProperty("Content-type",
            "application/x-www-form-urlencoded;charset=" + encoding);
    httpURLConnection.setRequestMethod("GET");
    return httpURLConnection;
}