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.sandklef.coachapp.http.HttpAccess.java

public void uploadTrainingPhaseVideo(String clubUri, String videoUuid, String fileName)
        throws HttpAccessException, IOException {

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String pathToOurFile = fileName;
    String urlServer = urlBase + HttpSettings.API_VERSION + HttpSettings.PATH_SEPARATOR
            + HttpSettings.VIDEO_URL_PATH + HttpSettings.UUID_PATH + videoUuid + HttpSettings.PATH_SEPARATOR
            + HttpSettings.UPLOAD_PATH;/*from   ww w  .  ja v  a2 s  . co m*/

    Log.d(LOG_TAG, "Upload server url: " + urlServer);
    Log.d(LOG_TAG, "Upload file:       " + fileName);

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;

    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));

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

    Log.d(LOG_TAG, "connection: " + connection + "  uploading data to video: " + videoUuid);

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

    //
    int timeout = LocalStorage.getInstance().getnetworkTimeout();
    Log.d(LOG_TAG, "timeout: " + timeout);
    connection.setConnectTimeout(timeout);
    connection.setReadTimeout(timeout);

    connection.setRequestProperty("X-Token", LocalStorage.getInstance().getLatestUserToken());
    connection.addRequestProperty("X-Instance", LocalStorage.getInstance().getCurrentClub());
    connection.setRequestProperty("Connection", "close");

    Log.d(LOG_TAG, " upload propoerties: " + connection.getRequestProperties());

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

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

    while (bytesRead > 0) {
        Log.d(LOG_TAG, " writing data to stream  (" + bytesRead + " / " + bytesAvailable + ")");
        outputStream.write(buffer, 0, bufferSize);
        Log.d(LOG_TAG, " writing data to stream  -");
        bytesAvailable = fileInputStream.available();
        Log.d(LOG_TAG, " writing data to stream  -");
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }
    outputStream.flush();
    outputStream.close();

    // Responses from the server (code and message)
    fileInputStream.close();

    int serverResponseCode = 0;

    long before = System.currentTimeMillis();
    try {
        Log.d(LOG_TAG, " ... writing done, getting response code");
        serverResponseCode = connection.getResponseCode();
        Log.d(LOG_TAG, " ... writing done, getting response message");
        String serverResponseMessage = connection.getResponseMessage();
        Log.d(LOG_TAG, "ServerCode:" + serverResponseCode);
        Log.d(LOG_TAG, "serverResponseMessage:" + serverResponseMessage);
    } catch (java.net.SocketTimeoutException e) {
        Log.d(LOG_TAG, " ... getting response code, got an exception, print stacktrace");
        e.printStackTrace();
        throw new HttpAccessException("Network timeout reached", e, HttpAccessException.NETWORK_SLOW);
    }
    long after = System.currentTimeMillis();
    long diff = after - before;
    Log.d(LOG_TAG, "diff: " + diff + "ms   " + diff / 1000 + "s");

    if (diff > LocalStorage.getInstance().getnetworkTimeout()) {
        throw new HttpAccessException("Network timeout reached", HttpAccessException.NETWORK_SLOW);
    }

    if (serverResponseCode >= 409) {
        throw new HttpAccessException("Failed uploading trainingphase video, access denied",
                HttpAccessException.CONFLICT_ERROR);
    }

    if (serverResponseCode < 500 && serverResponseCode >= 400) {
        throw new HttpAccessException("Failed uploading trainingphase video, access denied",
                HttpAccessException.ACCESS_ERROR);
    }

    try {
        Log.d(LOG_TAG, " ... disconnecting");
        connection.disconnect();
    } catch (Exception e) {
        Log.d(LOG_TAG, " ... disconnecting, got an exception, print stacktrace");
        e.printStackTrace();
    }
}

From source file:eu.fusepool.p3.transformer.client.TransformerClientImpl.java

@Override
public Entity transform(Entity entity, MimeType... acceptedFormats) {
    HttpURLConnection connection = null;
    try {/*from   w ww. j av  a2 s . co m*/
        final URL transfromerUrl = uri.toURL();
        connection = (HttpURLConnection) transfromerUrl.openConnection();
        connection.setRequestMethod("POST");
        String acceptHeaderValue = null;
        if (acceptedFormats.length > 0) {
            final StringWriter acceptString = new StringWriter();
            double q = 1;
            for (MimeType mimeType : acceptedFormats) {
                acceptString.write(mimeType.toString());
                acceptString.write("; q=");
                acceptString.write(Double.toString(q));
                q = q * 0.9;
                acceptString.write(", ");
            }
            acceptHeaderValue = acceptString.toString();
            connection.setRequestProperty("Accept", acceptHeaderValue);
        }

        connection.setRequestProperty("Content-Type", entity.getType().toString());
        if (entity.getContentLocation() != null) {
            connection.setRequestProperty("Content-Location", entity.getContentLocation().toString());
        }

        connection.setDoOutput(true);
        connection.setUseCaches(false);
        try (OutputStream out = connection.getOutputStream()) {
            entity.writeData(out);
        }
        final int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            return getResponseEntity(connection);
        }
        if ((responseCode == 202) || (responseCode == 201)) {
            final String location = connection.getHeaderField("Location");
            if (location == null) {
                throw new RuntimeException("No location header in first 202 response");
            }
            return getAsyncResponseEntity(new URL(transfromerUrl, location), acceptHeaderValue);
        }
        throw new UnexpectedResponseException(responseCode, getResponseEntity(connection));

    } catch (IOException e) {
        throw new RuntimeException("Cannot establish connection to " + uri.toString() + " !", e);
    } catch (MimeTypeParseException ex) {
        throw new RuntimeException("Error parsing MediaType returned from Server. ", ex);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:my.swingconnect.SwingConnectUI.java

public int uploadFile(String User, String Pass) {
    int set = 0;/*from www . j  ava  2  s  .c o m*/
    String upLoadServerUri = null;
    upLoadServerUri = "http://photo-drop.com/clientlogin.php";
    final String USER_AGENT = "Mozilla/5.0";
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    if (User.isEmpty() && Pass.isEmpty()) {

        System.out.println("Please enter the valid User and Pass :");

        return set;
    } else {

        try {
            //String upLoadServerUri = null;
            int serverResponseCode = 0;

            URL url = new URL(upLoadServerUri); //Passing the server complete URL

            // Open a HTTP connection to the URL
            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("User-Agent", USER_AGENT);
            conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
            //conn.setRequestProperty("Cookie", "Username=Mavericks;");
            String urlParameters = "Username=" + User + "&Password=" + Pass + "&submit=Login";
            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(urlParameters);
            dos.flush();
            dos.close();

            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + urlParameters);
            serverResponseCode = conn.getResponseCode();

            String serverResponseMessage = conn.getResponseMessage();

            System.out.println("HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                System.out.println("Posted success");
                set = 1;
            } else if (serverResponseCode == 401) {
                System.out.println("Invalid Login");

            } else {
                System.out.println("Error check");
            }

        } catch (MalformedURLException ex) {

            ex.printStackTrace();
            System.out.println("Error");

        } catch (Exception e) {

            e.printStackTrace();
            System.out.println("Error");

        }

        return set;

    }

}

From source file:com.docdoku.client.data.MainModel.java

private void downloadFileWithServlet(Component pParent, File pLocalFile, String pURL) throws IOException {
    System.out.println("Downloading file from servlet");
    ProgressMonitorInputStream in = null;
    OutputStream out = null;//from w  w w  .  ja va2 s  .com
    HttpURLConnection conn = null;
    try {
        //Hack for NTLM proxy
        //perform a head method to negociate the NTLM proxy authentication
        performHeadHTTPMethod(pURL);

        out = new BufferedOutputStream(new FileOutputStream(pLocalFile), Config.BUFFER_CAPACITY);
        URL url = new URL(pURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestMethod("GET");
        byte[] encoded = org.apache.commons.codec.binary.Base64
                .encodeBase64((getLogin() + ":" + getPassword()).getBytes("ISO-8859-1"));
        conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));
        conn.connect();
        int code = conn.getResponseCode();
        System.out.println("Download HTTP response code: " + code);
        in = new ProgressMonitorInputStream(pParent, I18N.BUNDLE.getString("DownloadMsg_part1"),
                new BufferedInputStream(conn.getInputStream(), Config.BUFFER_CAPACITY));
        ProgressMonitor pm = in.getProgressMonitor();
        pm.setMaximum(conn.getContentLength());
        byte[] data = new byte[Config.CHUNK_SIZE];
        int length;
        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }
        out.flush();
    } finally {
        out.close();
        in.close();
        conn.disconnect();
    }
}

From source file:iracing.webapi.IracingWebApi.java

private boolean forumLoginAndGetCookie() {
    try {/*w  ww .ja va  2  s .c o  m*/
        // Make a connect to the server
        URL url = new URL(FORUM_LOGIN_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.addRequestProperty(COOKIE, cookie);

        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(false);
        HttpURLConnection.setFollowRedirects(false);

        conn.connect();

        if (isMaintenancePage(conn))
            return false;

        String headerName;
        boolean containsCookie = false;
        for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equalsIgnoreCase(SET_COOKIE)) {
                containsCookie = true;
                addToCookieMap(conn.getHeaderField(i));
            }
        }
        if (containsCookie)
            createCookieFromMap();

        conn.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.plancake.api.client.PlancakeApiClient.java

/**
 * @param String request//w w w.jav  a2 s.  c o m
 * @param String httpMethod
 * @return String
 */
private String getResponse(String request, String httpMethod)
        throws MalformedURLException, IOException, PlancakeApiException {
    if (!(httpMethod.equals("GET")) && !(httpMethod.equals("POST"))) {
        throw new PlancakeApiException("httpMethod must be either GET or POST");
    }

    String urlParameters = "";

    if (httpMethod == "POST") {
        String[] requestParts = request.split("\\?");
        request = requestParts[0];
        urlParameters = requestParts[1];
    }

    URL url = new URL(request);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod(httpMethod);
    if (httpMethod == "POST") {
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    } else {
        connection.setRequestProperty("Content-Type", "text/plain");
    }
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
    connection.setUseCaches(false);
    connection.connect();

    if (httpMethod == "POST") {
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
    }

    StringBuffer text = new StringBuffer();
    InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());
    BufferedReader buff = new BufferedReader(in);
    String line = buff.readLine();
    while (line != null) {
        text.append(line + "\n");
        line = buff.readLine();
    }
    String response = text.toString();

    if (response.length() == 0) {
        throw new PlancakeApiException("the response is empty");
    }

    connection.disconnect();
    return response;
}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String queryDMSTest(String dms_endpoint, String body) throws UnsupportedEncodingException, IOException,
        KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

    HttpURLConnection connection = null;
    // Of course everything will go over HTTPS (here we trust anything, we do not check the certificate)
    SSLContext sc = null;/* www  . ja v  a2 s.  c o m*/
    try {
        sc = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e1) {

    }

    InputStream is;
    BufferedReader rd;
    char cbuf[] = new char[1000000];
    int len;

    String urlParameters = body; // test cookie is the user performing the evalaution
    // The array of resources to evaluate policies on must be included

    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
    int postDataLength = postData.length;
    URL url = new URL(dms_URL + "/" + dms_endpoint);
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");

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

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setRequestProperty("Cookie", cookie); // Include cookies (permissions evaluated for normal user, advanced user has the rights to evaluate)

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.write(postData);
        wr.close();

        // Get Response
        int err = connection.getResponseCode();
        if (err >= 200 && err < 300) {

            is = connection.getInputStream();
            //             
            rd = new BufferedReader(new InputStreamReader(is));
            //                //StringBuilder rd2 = new StringBuilder();

            len = rd.read(cbuf);
            String resp2 = String.valueOf(cbuf).substring(0, len - 1);
            rd.close();
            return resp2;

            //            char[] buffer = new char[1024*1024];
            //            StringBuilder output = new StringBuilder();
            //            int readLength = 0;
            //            while (readLength != -1) {
            //                readLength = rd.read(buffer, 0, buffer.length);
            //                if (readLength != -1) {
            //                    output.append(buffer, 0, readLength);
            //                }
            //            }

            //                return output.toString();
        }

    } catch (Exception e) {
        throw new java.net.ConnectException();
        //log 
    } finally {
        if (connection != null) {
            connection.disconnect();

        }
    }
    return null;
}

From source file:com.mendhak.gpslogger.senders.gdocs.GDocsHelper.java

private String CreateEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) {

    String fileId = null;/*  w w w . j  a  va  2  s .c  o m*/
    HttpURLConnection conn = null;

    String createFileUrl = "https://www.googleapis.com/drive/v2/files";

    String createFilePayload = "   {\n" + "             \"title\": \"" + fileName + "\",\n"
            + "             \"mimeType\": \"" + mimeType + "\",\n" + "             \"parents\": [\n"
            + "              {\n" + "               \"id\": \"" + parentFolderId + "\"\n" + "              }\n"
            + "             ]\n" + "            }";

    try {

        if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
            //Due to a pre-froyo bug
            //http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            System.setProperty("http.keepAlive", "false");
        }

        URL url = new URL(createFileUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "GPSLogger for Android");
        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/json");

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

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(createFilePayload);
        wr.flush();
        wr.close();

        fileId = null;

        String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream());

        JSONObject fileMetadataJson = new JSONObject(fileMetadata);
        fileId = fileMetadataJson.getString("id");
        Utilities.LogDebug("File created with ID " + fileId);

    } catch (Exception e) {

        System.out.println(e.getMessage());
        System.out.println(e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }

    }

    return fileId;
}

From source file:com.geotrackin.gpslogger.senders.gdocs.GDocsHelper.java

private String CreateEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) {

    String fileId = null;//from www. ja va2  s. com
    HttpURLConnection conn = null;

    String createFileUrl = "https://www.googleapis.com/drive/v2/files";

    String createFilePayload = "   {\n" + "             \"title\": \"" + fileName + "\",\n"
            + "             \"mimeType\": \"" + mimeType + "\",\n" + "             \"parents\": [\n"
            + "              {\n" + "               \"id\": \"" + parentFolderId + "\"\n" + "              }\n"
            + "             ]\n" + "            }";

    try {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
            //Due to a pre-froyo bug
            //http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            System.setProperty("http.keepAlive", "false");
        }

        URL url = new URL(createFileUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "GPSLogger for Android");
        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/json");

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

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(createFilePayload);
        wr.flush();
        wr.close();

        fileId = null;

        String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream());

        JSONObject fileMetadataJson = new JSONObject(fileMetadata);
        fileId = fileMetadataJson.getString("id");
        tracer.debug("File created with ID " + fileId + " of type " + mimeType);

    } catch (Exception e) {

        System.out.println(e.getMessage());
        System.out.println(e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }

    }

    return fileId;
}

From source file:iracing.webapi.IracingWebApi.java

private SendPrivateMessageResult sendPrivateMessage(int customerDefinitionType, String customer, String subject,
        String message) throws IOException, LoginException {
    if (!cookieMap.containsKey(JSESSIONID)) {
        if (login() != LoginResponse.Success)
            return SendPrivateMessageResult.UNABLE_TO_LOGIN;
    }//from  w w  w.  j a v a  2s  . c om
    SendPrivateMessageResult output = SendPrivateMessageResult.UNKNOWN_ERROR;
    if (!cookieMap.containsKey(JFORUMSESSIONID)) {
        if (!forumLoginAndGetCookie())
            return SendPrivateMessageResult.UNABLE_TO_LOGIN;
    }
    try {
        // Make a connection
        URL url = new URL(FORUM_POST_PAGE_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        //multipart/form-data
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        //conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDRY);

        conn.addRequestProperty(COOKIE, cookie);

        StringBuilder data = new StringBuilder();

        // set the multipart form data parameters
        addMultipartFormData(data, "action", "sendSave");
        addMultipartFormData(data, "module", "pm");
        addMultipartFormData(data, "preview", "0");
        addMultipartFormData(data, "start", null);
        if (customerDefinitionType == CUSTOMER_DEFINITION_TYPE_ID) {
            addMultipartFormData(data, "toUsername", null);
            addMultipartFormData(data, "toUserId", customer);
        } else if (customerDefinitionType == CUSTOMER_DEFINITION_TYPE_NAME) {
            addMultipartFormData(data, "toUsername", customer);
            addMultipartFormData(data, "toUserId", null);
        }
        addMultipartFormData(data, "disa1ble_html", "on");
        addMultipartFormData(data, "attach_sig", "on");
        addMultipartFormData(data, "subject", subject);
        addMultipartFormData(data, "message", message);
        addMultipartFormData(data, "addbbcode24", "#444444");
        addMultipartFormData(data, "addbbcode26", "12");
        addMultipartFormData(data, "helpbox", "Italic Text: [i]Text[/i]  (alt+i)");

        data.append(twoHyphens).append(BOUNDRY).append(twoHyphens);
        DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
        try {
            dataOS.writeBytes(data.toString());
            dataOS.flush();
        } finally {
            dataOS.close();
        }

        conn.connect();

        if (isMaintenancePage(conn))
            return SendPrivateMessageResult.UNABLE_TO_LOGIN;

        // Ensure we got the HTTP 200 response code
        int responseCode = conn.getResponseCode();
        if (responseCode != 200) {
            throw new Exception(String.format("Received the response code %d from the URL %s : %s",
                    responseCode, url, conn.getResponseMessage()));
        }

        String response = getResponseText(conn);
        //            System.out.println(response);

        if (response.contains("Your message was successfully sent.")) {
            output = SendPrivateMessageResult.SUCCESS;
        } else if (response.contains(
                "Could not determine the user id. Please check if you typed the username correctly and try again.")) {
            output = SendPrivateMessageResult.USER_NOT_FOUND;
        } else if (response.contains(
                "Sorry, but this users inbox is currently full and cannot receive private messages at this time.")) {
            output = SendPrivateMessageResult.MAILBOX_FULL;
        }

        conn.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return output;
}