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:com.bjorsond.android.timeline.sync.ServerUploader.java

protected static void uploadFile(String locationFilename, String saveFilename) {
    System.out.println("saving " + locationFilename + "!! ");
    if (!saveFilename.contains("."))
        saveFilename = saveFilename + Utilities.getExtension(locationFilename);

    if (!fileExistsOnServer(saveFilename)) {

        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;

        String pathToOurFile = locationFilename;
        String urlServer = "http://folk.ntnu.no/bjornava/upload/upload.php";
        //         String urlServer = "http://timelinegamified.appspot.com/upload.php";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024 * 1024;

        try {//from  w  ww .ja va2 s .  c  o m
            FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));

            URL url = new URL(urlServer);
            connection = (HttpURLConnection) url.openConnection();

            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            // Enable POST method
            connection.setRequestMethod("POST");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + saveFilename + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();

            System.out.println("Server response: " + serverResponseCode + " Message: " + serverResponseMessage);
        } catch (Exception ex) {
            //Exception handling
        }
    } else {
        System.out.println("image exists on server");
    }
}

From source file:com.comcast.cmb.test.tools.CNSTestingUtils.java

public static String sendHttpMessage(String endpoint, String message) throws Exception {

    if ((message == null) || (endpoint == null)) {
        throw new Exception("Message and Endpoint must both be set");
    }/*from   w w  w.java2  s  .c om*/

    String newPostBody = message;
    byte newPostBodyBytes[] = newPostBody.getBytes();

    URL url = new URL(endpoint);

    logger.info(">> " + url.toString());

    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    con.setRequestMethod("GET"); // POST no matter what
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setFollowRedirects(false);
    con.setUseCaches(true);

    logger.info(">> " + "GET");

    //con.setRequestProperty("content-length", newPostBody.length() + "");
    con.setRequestProperty("host", url.getHost());

    con.connect();

    logger.info(">> " + newPostBody);

    int statusCode = con.getResponseCode();

    BufferedInputStream responseStream;

    logger.info("StatusCode:" + statusCode);

    if (statusCode != 200 && statusCode != 201) {

        responseStream = new BufferedInputStream(con.getErrorStream());
    } else {
        responseStream = new BufferedInputStream(con.getInputStream());
    }

    int b;
    String response = "";

    while ((b = responseStream.read()) != -1) {
        response += (char) b;
    }

    logger.info("response:" + response);
    return response;
}

From source file:com.tonchidot.nfc_contact_exchanger.lib.PictureUploader.java

private String doFileUploadJson(String url, String fileParamName, byte[] data) {
    try {//from   w  w  w.j  av a2s.c om
        String boundary = "BOUNDARY" + new Date().getTime() + "BOUNDARY";
        String lineEnd = "\r\n";
        String twoHyphens = "--";

        URL connUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) connUrl.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"" + fileParamName + "\";filename=\"photo.jpg\""
                + lineEnd);
        dos.writeBytes(lineEnd);
        dos.write(data, 0, data.length);
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        dos.flush();
        dos.close();

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        return result.toString();
    } catch (IOException e) {
        if (Config.LOGD) {
            Log.d(TAG, "IOException : " + e);
        }
    }
    return null;
}

From source file:eu.crushedpixel.littlstar.api.upload.S3Uploader.java

/**
 * Executes a multipart form upload to the S3 Bucket as described in
 * <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTExamples.html">the AWS Documentation</a>.
 * @param s3UploadProgressListener An S3UploadProgressListener which is called whenever
 *                               bytes are written to the outgoing connection. May be null.
 * @throws IOException in case of a problem or the connection was aborted
 * @throws ClientProtocolException in case of an http protocol error
 *//*from ww  w.  j a  va 2 s. c o m*/
public void uploadFileToS3(S3UploadProgressListener s3UploadProgressListener)
        throws IOException, ClientProtocolException {
    //unfortunately, we can't use Unirest to execute the call, because there is no support
    //for Progress listeners (yet). See https://github.com/Mashape/unirest-java/issues/26

    int bufferSize = 1024;

    //opening a connection to the S3 Bucket
    HttpURLConnection urlConnection = (HttpURLConnection) new URL(s3_bucket).openConnection();
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setChunkedStreamingMode(bufferSize);
    urlConnection.setRequestProperty("Connection", "Keep-Alive");
    urlConnection.setRequestProperty("Cache-Control", "no-cache");
    String boundary = "*****";
    urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    //writing the request headers
    DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());

    String newline = "\r\n";
    String twoHyphens = "--";
    dos.writeBytes(twoHyphens + boundary + newline);

    String attachmentName = "file";
    String attachmentFileName = "file";

    dos.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\""
            + attachmentFileName + "\"" + newline);
    dos.writeBytes(newline);

    //sending the actual file
    byte[] buf = new byte[bufferSize];

    FileInputStream fis = new FileInputStream(file);
    long totalBytes = fis.getChannel().size();
    long writtenBytes = 0;

    int len;
    while ((len = fis.read(buf)) != -1) {
        dos.write(buf);
        writtenBytes += len;

        s3UploadProgressListener.onProgressUpdated(new S3UpdateProgressEvent(writtenBytes, totalBytes,
                (float) ((double) writtenBytes / totalBytes)));

        if (interrupt) {
            fis.close();
            dos.close();
            return;
        }
    }

    fis.close();

    //finish the call
    dos.writeBytes(newline);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + newline);

    dos.close();

    urlConnection.disconnect();
}

From source file:org.exoplatform.utils.image.ExoPicassoDownloader.java

@Override
public Response load(Uri uri, int networkPolicy) throws IOException {
    // TODO use networkPolicy as in com.squareup.picasso.UrlConnectionDownloader
    // https://github.com/square/picasso/blob/picasso-parent-2.5.2/picasso/src/main/java/com/squareup/picasso/UrlConnectionDownloader.java
    HttpURLConnection connection = connection(uri);
    connection.setInstanceFollowRedirects(true);
    connection.setUseCaches(true);

    int responseCode = connection.getResponseCode();
    // Handle HTTP redirections that are not managed by HttpURLConnection
    // automatically, e.g. HTTP -> HTTPS
    // TODO consider using OkHttp instead
    if (responseCode >= 300 && responseCode < 400) {
        String location = connection.getHeaderField("Location");
        connection.disconnect();/*from   ww  w  . j  av a 2 s.c  o m*/
        connection = connection(Uri.parse(location));
        connection.setInstanceFollowRedirects(true);
        connection.setUseCaches(true);
        responseCode = connection.getResponseCode();
    }
    // Either the original or the new request have failed -> error
    if (responseCode >= 300) {
        connection.disconnect();
        throw new ResponseException(responseCode + " " + connection.getResponseMessage(), networkPolicy,
                responseCode);
    }

    long contentLength = connection.getHeaderFieldInt("Content-Length", -1);
    // boolean fromCache =
    // parseResponseSourceHeader(connection.getHeaderField(RESPONSE_SOURCE));
    boolean fromCache = false;

    return new Response(connection.getInputStream(), fromCache, contentLength);
}

From source file:eu.creatingfuture.propeller.webLoader.servlets.WebRequestServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.addHeader("Access-Control-Allow-Origin", "*");
    String getUrl = req.getParameter("get");
    if (getUrl == null) {
        resp.sendError(400);/*from w  w w .ja  v a2s  .c om*/
        return;
    }
    logger.info(getUrl);
    URL url;
    HttpURLConnection connection = null;
    try {
        url = new URL(getUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setUseCaches(false);

        resp.setContentType(connection.getContentType());
        resp.setContentLengthLong(connection.getContentLengthLong());
        logger.log(Level.INFO, "Content length: {0} response code: {1} content type: {2}", new Object[] {
                connection.getContentLengthLong(), connection.getResponseCode(), connection.getContentType() });
        resp.setStatus(connection.getResponseCode());
        IOUtils.copy(connection.getInputStream(), resp.getOutputStream());
    } catch (IOException ioe) {
        resp.sendError(500, ioe.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.gmail.ferusgrim.util.UuidGrabber.java

public Map<String, UUID> call() throws Exception {
    JSONParser jsonParser = new JSONParser();
    Map<String, UUID> responseMap = new HashMap<String, UUID>();

    URL url = new URL("https://api.mojang.com/profiles/minecraft");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setUseCaches(false);
    connection.setDoInput(true);//from   w  w  w. j  ava  2 s .c om
    connection.setDoOutput(true);

    String body = JSONArray.toJSONString(this.namesToLookup);

    OutputStream stream = connection.getOutputStream();
    stream.write(body.getBytes());
    stream.flush();
    stream.close();

    JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));

    for (Object profile : array) {
        JSONObject jsonProfile = (JSONObject) profile;
        String id = (String) jsonProfile.get("id");
        String name = (String) jsonProfile.get("name");
        UUID uuid = Grab.uuidFromResult(id);
        responseMap.put(name, uuid);
    }

    return responseMap;
}

From source file:acc.healthapp.notification.HttpRequest.java

/**
 * Post the request/*w  ww .ja va 2 s .  com*/
 * @param url where to post to
 * @param requestBody the body of the request
 * @throws IOException
 */
public void doPost(String url, String requestBody) throws IOException {
    Log.i("", "HTTP request. body: " + requestBody);

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(requestBody.getBytes().length);
    conn.setRequestMethod("POST");
    for (int i = 0; i < mHeaders.size(); i++) {
        conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i));
    }
    OutputStream out = null;
    try {
        out = conn.getOutputStream();
        out.write(requestBody.getBytes());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }

    responseCode = conn.getResponseCode();

    InputStream inputStream = null;
    try {
        if (responseCode == 200) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }
        responseBody = getString(inputStream);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }

    Log.i("", "HTTP response. body: " + responseBody);

    conn.disconnect();
}

From source file:com.tdevelopers.questo.Pushes.HttpRequest.java

/**
 * Post the request//  ww  w . j a v  a  2 s .c o  m
 *
 * @param url         where to post to
 * @param requestBody the body of the request
 * @throws IOException
 */
public void doPost(String url, String requestBody) throws IOException {
    Log.i(LoggingService.LOG_TAG, "HTTP request. body: " + requestBody);
    Log.i(LoggingService.LOG_TAG, "header" + mHeaders.toString());
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(requestBody.getBytes().length);
    conn.setRequestMethod("POST");
    for (int i = 0; i < mHeaders.size(); i++) {
        conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i));
    }
    OutputStream out = null;
    try {
        out = conn.getOutputStream();
        out.write(requestBody.getBytes());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }

    responseCode = conn.getResponseCode();

    InputStream inputStream = null;
    try {
        if (responseCode == 200) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }
        responseBody = getString(inputStream);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }

    Log.i(LoggingService.LOG_TAG, "HTTP response. body: " + responseBody);

    conn.disconnect();
}

From source file:com.google.android.gcm.demo.logic.HttpRequest.java

/**
 * Post the request// w  ww  .ja va  2 s  . c o m
 * @param url where to post to
 * @param requestBody the body of the request
 * @throws IOException
 */
public void doPost(String url, String requestBody) throws IOException {
    Log.i(LoggingService.LOG_TAG, "HTTP request. body: " + requestBody);

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(requestBody.getBytes().length);
    conn.setRequestMethod("POST");
    for (int i = 0; i < mHeaders.size(); i++) {
        conn.setRequestProperty(mHeaders.keyAt(i), mHeaders.valueAt(i));
    }
    OutputStream out = null;
    try {
        out = conn.getOutputStream();
        out.write(requestBody.getBytes());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }

    responseCode = conn.getResponseCode();

    InputStream inputStream = null;
    try {
        if (responseCode == 200) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }
        responseBody = getString(inputStream);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }

    Log.i(LoggingService.LOG_TAG, "HTTP response. body: " + responseBody);

    conn.disconnect();
}