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:iics.Connection.java

public String excutePost(String targetURL, String urlParameters) {

    URL url;//from   ww w . j a  v  a2s .co m
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        //Get Response   
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            if (!line.equals("")) {
                response.append(line);
            }
            //response.append('\r');
        }
        rd.close();

        // System.out.println("gigig " + response.toString());
        if (response.toString().substring(0, 8).equals("Response")) {
            String[] dett = response.toString().split("~~~");
            det = dett[1];
            create_dir();
            openweb(f.toString());
        } else {
            //System.out.println("err "+ex.getMessage());
            JOptionPane.showMessageDialog(null,
                    "                 An error occured!! \n Try again later or contact your system admin for help.");
            close_loda();
        }
        return response.toString();

    } catch (Exception e) {

        JOptionPane.showMessageDialog(null,
                "                 An error occured!! \n Contact your system admin for help.", null,
                JOptionPane.WARNING_MESSAGE);
        close_loda();
        return null;

    } finally {

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

From source file:com.googlecode.fascinator.portal.quartz.ExternalJob.java

/**
 * The real work happens here/*from w w  w . j  av  a2 s  .  co  m*/
 *
 */
private void runJob() {
    HttpURLConnection conn = null;
    log.debug("Job firing: '{}'", name);

    try {
        // Open tasks... much simpler
        if (token == null) {
            conn = (HttpURLConnection) url.openConnection();

            // Secure tasks
        } else {
            String param = "token=" + URLEncoder.encode(token, "UTF-8");

            // Prepare our request
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", "" + Integer.toString(param.getBytes().length));
            conn.setUseCaches(false);
            conn.setDoOutput(true);

            // Send request
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(param);
            wr.flush();
            wr.close();
        }

        // Get Response
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            log.error("Error hitting external script: {}", conn.getResponseMessage());
        }
    } catch (IOException ex) {
        log.error("Error connecting to URL: ", ex);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.mycompany.grupo6ti.GenericResource.java

@GET
@Produces("application/json")
@Path("/obtenerOc/{id}")
public String obtenerOc(@PathParam("id") String id)

{

    try {/*from  w w w . j  ava 2s  .c o  m*/
        URL url = new URL("http://localhost:83/obtener/" + id);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        InputStream is;
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        conn.setUseCaches(true);
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        if (conn.getResponseCode() >= 400) {
            is = conn.getErrorStream();
        } else {
            is = conn.getInputStream();
        }
        String result2 = "";
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = rd.readLine()) != null) {
            result2 += line;
        }
        rd.close();

        return result2;

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

    return "error";
}

From source file:com.flyingspaniel.nava.request.Request.java

protected HttpURLConnection prepareConnection(HttpURLConnection conn) {
    conn.setRequestProperty(ACCEPT_CHARSET, options.getString("acceptCharset", URLEncoding.UTF8_CHARSET));
    conn.setInstanceFollowRedirects(options.getBoolean("followRedirect", true));
    conn.setUseCaches(options.getBoolean("useCaches", true));

    doAuth(conn);/*w  ww.j  av  a 2s  .c o m*/
    headersMMap.applyHeadersToConnection(conn);

    int timeout = options.getInt("timeout", 2000);
    conn.setConnectTimeout(timeout);
    conn.setReadTimeout(options.getInt("readTimeout", timeout));

    conn.setDoInput(method.doesInput());
    conn.setDoOutput(method.doesOutput());

    // Since HTTPMethod is an enum with an acceptable protocol, this exception "cannot happen"
    try {
        conn.setRequestMethod(method.getMethodName());
    } catch (ProtocolException e) {
        throw new RuntimeException(e); // cannot happen
    }

    return conn;
}

From source file:edu.mda.bioinfo.ids.DownloadFiles.java

private void downloadFromHttpToFile(String theURL, String theParameters, String theFile) throws IOException {
    // both in milliseconds
    //int connectionTimeout = 1000 * 60 * 3;
    //int readTimeout = 1000 * 60 * 3;
    try {/*from w w  w.  jav a  2 s.  c o  m*/
        URL myURL = new URL(theURL);
        HttpURLConnection connection = (HttpURLConnection) myURL.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        //connection.setRequestProperty("charset", "utf-8");
        if (null != theParameters) {
            System.out.println("Content-Length " + Integer.toString(theParameters.getBytes().length));
            connection.setRequestProperty("Content-Length",
                    "" + Integer.toString(theParameters.getBytes().length));
        }
        connection.setUseCaches(false);
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            if (null != theParameters) {
                wr.write(theParameters.getBytes());
            }
            wr.flush();
            File myFile = new File(theFile);
            System.out.println("Requesting " + myURL);
            FileUtils.copyInputStreamToFile(connection.getInputStream(), myFile);
            System.out.println("Downloaded " + myURL);
        } catch (IOException rethrownExp) {
            InputStream errorStr = connection.getErrorStream();
            if (null != errorStr) {
                System.err.println("Error stream returned: " + IOUtils.toString(errorStr));
            } else {
                System.err.println("No error stream returned");
            }
            throw rethrownExp;
        }
    } catch (IOException rethrownExp) {
        System.err.println("exception " + rethrownExp.getMessage() + " thrown while downloading " + theURL
                + " to " + theFile);
        throw rethrownExp;
    }
}

From source file:easyshop.downloadhelper.HttpPageGetter.java

public HttpPage getURLOnly(WebLink url) {

    log.debug("getURL(" + url + ")");

    if (url.getUrlStr() == null) {
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new HttpPage(null, null, conRes, null);
    }/*from   www  .ja  v a2s  .  co m*/

    URL requestedURL = null;
    URL referer = null;
    try {
        requestedURL = new URL(url.getUrlStr());
        log.debug("Creating HTTP connection to " + requestedURL);
        HttpURLConnection conn = (HttpURLConnection) requestedURL.openConnection();
        if (referer != null) {
            log.debug("Setting Referer header to " + referer);
            conn.setRequestProperty("Referer", referer.toExternalForm());
        }

        if (userAgent != null) {
            log.debug("Setting User-Agent to " + userAgent);
            conn.setRequestProperty("User-Agent", userAgent);
        }

        conn.setUseCaches(false);

        log.debug("Opening URL");
        long startTime = System.currentTimeMillis();
        conn.connect();

        String resp = conn.getResponseMessage();
        log.debug("Remote server response: " + resp);

        int code = conn.getResponseCode();

        if (code != 200) {
            log.error("Could not get connection for code=" + code);
            System.err.println("Could not get connection for code=" + code);
        }
        ConnResponse conRes = new ConnResponse(conn.getContentType(), null, 0, 0, code);
        conn.disconnect();
        return new HttpPage(requestedURL.toExternalForm(), null, conRes, conRes.getCharSet());
    }

    catch (IOException ioe) {
        log.warn("Caught IO Exception: " + ioe.getMessage(), ioe);
        failureCount++;
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
    } catch (Exception e) {
        log.warn("Caught Exception: " + e.getMessage(), e);
        failureCount++;
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
    }
}

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

/**
 * Post//from   w  ww.j a v a2 s .c  om
 *
 * @return
 * @throws ProtocolException
 */
private HttpURLConnection createConnection(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.setDoInput(true); // ? post?
    httpURLConnection.setDoOutput(true); // ? post?
    httpURLConnection.setUseCaches(false);// ?
    httpURLConnection.setRequestProperty("Content-type",
            "application/x-www-form-urlencoded;charset=" + encoding);
    httpURLConnection.setRequestMethod("POST");
    return httpURLConnection;
}

From source file:edu.ku.brc.specify.web.HttpLargeFileTransfer.java

/**
 * @param fileName//from w  w w  .jav  a 2 s  . c om
 * @param urlStr
 * @param isSiteFile
 * @param propChgListener
 */
public void transferFile(final String fileName, final String urlStr, final boolean isSiteFile,
        final PropertyChangeListener propChgListener) {

    final String prgName = HttpLargeFileTransfer.class.toString();

    final File file = new File(fileName);
    if (file.exists()) {
        final long fileSize = file.length();
        if (fileSize > 0) {
            SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
                protected String errorMsg = null;
                protected FileInputStream fis = null;
                protected OutputStream fos = null;
                protected int nChunks = 0;

                /* (non-Javadoc)
                 * @see javax.swing.SwingWorker#doInBackground()
                 */
                @Override
                protected Integer doInBackground() throws Exception {
                    try {
                        Thread.sleep(100);
                        fis = new FileInputStream(file);

                        nChunks = (int) (fileSize / MAX_CHUNK_SIZE);
                        if (fileSize % MAX_CHUNK_SIZE > 0) {
                            nChunks++;
                        }

                        byte[] buf = new byte[BUFFER_SIZE];
                        long bytesRemaining = fileSize;

                        String clientID = String.valueOf((long) (Long.MIN_VALUE * Math.random()));

                        URL url = new URL(urlStr);

                        UIRegistry.getStatusBar().setProgressRange(prgName, 0, nChunks);

                        for (int i = 0; i < nChunks; i++) {
                            firePropertyChange(prgName, i - 1, i == nChunks - 1 ? Integer.MAX_VALUE : i);
                            if (i == nChunks - 1) {
                                Thread.sleep(500);
                                int x = 0;
                                x++;
                            }

                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            conn.setRequestMethod("PUT");
                            conn.setDoOutput(true);
                            conn.setDoInput(true);
                            conn.setUseCaches(false);

                            int chunkSize = (int) ((bytesRemaining > MAX_CHUNK_SIZE) ? MAX_CHUNK_SIZE
                                    : bytesRemaining);
                            bytesRemaining -= chunkSize;

                            conn.setRequestProperty("Content-Type", "application/octet-stream");
                            conn.setRequestProperty("Content-Length", String.valueOf(chunkSize));

                            conn.setRequestProperty(CLIENT_ID_HEADER, clientID);
                            conn.setRequestProperty(FILE_NAME_HEADER, fileName);
                            conn.setRequestProperty(FILE_CHUNK_COUNT_HEADER, String.valueOf(nChunks));
                            conn.setRequestProperty(FILE_CHUNK_HEADER, String.valueOf(i));
                            conn.setRequestProperty(SERVICE_NUMBER, "10");
                            conn.setRequestProperty(IS_SITE_FILE, Boolean.toString(isSiteFile));

                            fos = conn.getOutputStream();

                            //UIRegistry.getStatusBar().setProgressRange(prgName, 0, (int)((double)chunkSize / BUFFER_SIZE));
                            int cnt = 0;
                            int bytesRead = 0;
                            while (bytesRead < chunkSize) {
                                int read = fis.read(buf);
                                if (read == -1) {
                                    break;

                                } else if (read > 0) {
                                    bytesRead += read;
                                    fos.write(buf, 0, read);
                                }
                                cnt++;
                                //firePropertyChange(prgName, cnt-1, cnt);
                            }
                            fos.close();

                            if (conn.getResponseCode() != HttpServletResponse.SC_OK) {
                                System.err.println(
                                        conn.getResponseMessage() + " " + conn.getResponseCode() + " ");
                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(conn.getErrorStream()));
                                String line = null;
                                StringBuilder sb = new StringBuilder();
                                while ((line = in.readLine()) != null) {
                                    sb.append(line);
                                    sb.append("\n");
                                }
                                System.out.println(sb.toString());
                                in.close();

                            } else {
                                System.err.println("OK");
                            }
                            //UIRegistry.getStatusBar().setProgressRange(prgName, 0, nChunks);
                            firePropertyChange(prgName, i - 1, i == nChunks - 1 ? Integer.MAX_VALUE : i);
                        }

                    } catch (IOException ex) {
                        errorMsg = ex.toString();
                    }

                    //firePropertyChange(prgName, 0, 100);
                    return null;
                }

                @Override
                protected void done() {
                    super.done();

                    UIRegistry.getStatusBar().setProgressDone(prgName);

                    UIRegistry.clearSimpleGlassPaneMsg();

                    if (StringUtils.isNotEmpty(errorMsg)) {
                        UIRegistry.showError(errorMsg);
                    }

                    if (propChgListener != null) {
                        propChgListener.propertyChange(
                                new PropertyChangeEvent(HttpLargeFileTransfer.this, "Done", 0, 1));
                    }
                }
            };

            final JStatusBar statusBar = UIRegistry.getStatusBar();
            statusBar.setIndeterminate(HttpLargeFileTransfer.class.toString(), true);

            UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("Transmitting..."), 24);

            backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(final PropertyChangeEvent evt) {
                    System.out.println(evt.getPropertyName() + "  " + evt.getNewValue());
                    if (prgName.equals(evt.getPropertyName())) {
                        Integer value = (Integer) evt.getNewValue();
                        if (value == Integer.MAX_VALUE) {
                            statusBar.setIndeterminate(prgName, true);
                            UIRegistry.writeSimpleGlassPaneMsg(
                                    getLocalizedMessage("Transfering data into the database."), 24);

                        } else {
                            statusBar.setValue(prgName, value);
                        }
                    }
                }
            });
            backupWorker.execute();

        } else {
            // file doesn't exist
        }
    } else {
        // file doesn't exist
    }
}

From source file:com.huixueyun.tifenwang.api.net.HttpEngine.java

/**
 * ?connection// w  ww  . ja va  2s  .c o m
 *
 * @param paramUrl ??
 * @return HttpURLConnection
 */
private HttpURLConnection getConnection(String paramUrl) {
    HttpURLConnection connection = null;
    // ?connection
    try {
        // ??URL
        URL url = new URL(SERVER_URL + paramUrl);
        // ?URL
        connection = (HttpURLConnection) url.openConnection();
        // ?
        connection.setRequestMethod(REQUEST_MOTHOD);
        // ??POST?true
        connection.setDoInput(true);
        // ??POST?
        connection.setDoOutput(true);
        // ?
        connection.setUseCaches(false);
        // 
        connection.setReadTimeout(TIME_OUT);
        connection.setConnectTimeout(TIME_OUT);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Connection", "keep-alive");
        connection.setRequestProperty("Response-Type", "json");
        connection.setChunkedStreamingMode(0);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return connection;
}

From source file:lucee.commons.io.res.type.s3.S3.java

public HttpURLConnection preput(String bucketName, String objectName, int acl, String contentType)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException {
    bucketName = checkBucket(bucketName);
    objectName = checkObjectName(objectName);

    String dateTimeString = Util.toHTTPTimeString();
    // Create a canonical string to send based on operation requested 
    String cs = "PUT\n\n" + contentType + "\n" + dateTimeString + "\nx-amz-acl:" + toStringACL(acl) + "\n/"
            + bucketName + "/" + objectName;
    String signature = createSignature(cs, getSecretAccessKeyValidate(), "iso-8859-1");

    String strUrl = "http://" + bucketName + "." + host + "/" + objectName;
    if (Util.hasUpperCase(bucketName))
        strUrl = "http://" + host + "/" + bucketName + "/" + objectName;

    URL url = new URL(strUrl);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");

    conn.setFixedLengthStreamingMode(227422142);
    conn.setDoOutput(true);/* w ww .j  a v a2s .co  m*/
    conn.setUseCaches(false);
    conn.setRequestProperty("CONTENT-TYPE", contentType);
    conn.setRequestProperty("USER-AGENT", "S3 Resource");
    //conn.setRequestProperty("Transfer-Encoding", "chunked" );
    conn.setRequestProperty("Date", dateTimeString);
    conn.setRequestProperty("x-amz-acl", toStringACL(acl));
    conn.setRequestProperty("Authorization", "AWS " + getAccessKeyIdValidate() + ":" + signature);
    return conn;
}