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:io.confluent.kafkarest.tools.ProducerPerformance.java

@Override
protected void doIteration(PerformanceStats.Callback cb) {
    HttpURLConnection connection = null;
    try {/*from   www  .ja v a  2s .c o m*/
        URL url = new URL(targetUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", Versions.KAFKA_MOST_SPECIFIC_DEFAULT);
        connection.setRequestProperty("Content-Length", requestEntityLength);

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

        OutputStream os = connection.getOutputStream();
        os.write(requestEntity);
        os.flush();
        os.close();

        int responseStatus = connection.getResponseCode();
        if (responseStatus >= 400) {
            InputStream es = connection.getErrorStream();
            ErrorMessage errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class);
            es.close();
            throw new RuntimeException(String.format("Unexpected HTTP error status %d: %s", responseStatus,
                    errorMessage.getMessage()));
        }
        InputStream is = connection.getInputStream();
        while (is.read(buffer) > 0) {
            // Ignore output, just make sure we actually receive it
        }
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    cb.onCompletion(recordsPerIteration, bytesPerIteration);
}

From source file:foam.starwisp.NetworkManager.java

private void Post(String u, String type, String data, String CallbackName) {
    try {/*from w  w  w.  j  a v  a  2  s. c  o  m*/
        Log.i("starwisp", "posting: " + u);
        URL url = new URL(u);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setUseCaches(false);
        con.setReadTimeout(100000 /* milliseconds */);
        con.setConnectTimeout(150000 /* milliseconds */);
        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("data", data));

        OutputStream os = con.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(getQuery(params));
        writer.flush();
        writer.close();
        os.close();

        // Starts the query
        con.connect();
        m_RequestHandler.sendMessage(
                Message.obtain(m_RequestHandler, 0, new ReqMsg(con.getInputStream(), type, CallbackName)));

    } catch (Exception e) {
        Log.i("starwisp", e.toString());
        e.printStackTrace();
    }
}

From source file:com.wyp.module.controller.LicenseController.java

/**
 * wslicense//from  www .j a v  a  2 s . c o  m
 * 
 * @param properties
 * @return
 */
private String getCitrixLicense(String requestJson) {
    String licenses = "";
    OutputStreamWriter out = null;
    InputStream is = null;
    long start = System.currentTimeMillis();
    try {
        // ws url
        URL url = new URL(map.get("address"));
        // ws connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", " application/json");
        connection.setRequestMethod("POST");
        connection.connect();
        out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        out.append(requestJson);
        out.flush();
        // response string
        is = connection.getInputStream();
        int length = is.available();
        if (0 < length) {
            long end = System.currentTimeMillis();
            System.out.println("?" + (end - start));
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuilder tempStr = new StringBuilder();
            String temp = "";
            while ((temp = reader.readLine()) != null) {
                tempStr.append(temp);
            }
            licenses = tempStr.toString(); // utf-8?
            System.out.println(licenses);
        }
    } catch (IOException e) {
        String eMsg = e.getMessage();
        if ("Read timed out".equals(eMsg) || "Connection timed out: connect".equals(eMsg)
                || "Software caused connection abort: recv failed".equals(eMsg)) {
            long end = System.currentTimeMillis();
            System.out.println(eMsg + (end - start));
            licenses = "TIMEOUT";
        }
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (is != null) {
                is.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    System.out.println(licenses);
    return licenses;
}

From source file:be.wimsymons.intellij.polopolyimport.PPImporter.java

private void postData(final String name, final Reader reader, final String contentType,
        final String extraParams) throws IOException {
    Writer writer = null;/*from  w w  w . j  a va  2  s  .  c  o  m*/
    LOGGER.info("Doing HTTP POST for " + name);
    try {
        URL httpURL = buildURL(target, extraParams);

        HttpURLConnection httpConnection = (HttpURLConnection) httpURL.openConnection();
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);
        httpConnection.setUseCaches(false);
        httpConnection.setRequestMethod("PUT");
        httpConnection.setRequestProperty("Content-Type", contentType);
        httpConnection.setConnectTimeout(2000);
        httpConnection.setReadTimeout(60000);
        httpConnection.connect();

        if (contentType.contains("UTF-8")) {
            copyAndFlush(reader, httpConnection.getOutputStream());
        } else {
            writer = new OutputStreamWriter(httpConnection.getOutputStream());
            CharStreams.copy(reader, writer);
            writer.flush();
        }

        int responseCode = httpConnection.getResponseCode();
        String responseMessage = httpConnection.getResponseMessage();
        if (responseCode < 200 || responseCode >= 300) {
            failureCount++;
            PPImportPlugin.doNotify("Import of " + name + " failed: " + responseCode + " - " + responseMessage
                    + "\nCheck the server log for more details.", NotificationType.ERROR);
        } else {
            successCount++;
        }
    } catch (IOException e) {
        failureCount++;
        PPImportPlugin.doNotify("Import of " + name + " failed: " + e.getMessage(), NotificationType.ERROR);
    } finally {
        Closeables.close(reader, true);
        Closeables.close(writer, true);
    }
}

From source file:TargetsAPI.java

/**
 * Send the POST request to the Wikitude Cloud Targets API.
 * //from w  ww .  j  av a2  s  .c  om
 * <b>Remark</b>: We are not using any external libraries for sending HTTP
 * requests, to be as independent as possible. Libraries like Apache
 * HttpComponents (included in Android already) make it a lot easier to
 * interact with HTTP connections.
 * 
 * @param body
 *            The JSON body that is sent in the request.
 * @return The response from the server, in JSON format
 * 
 * @throws IOException
 *             when the server cannot serve the request for any reason, or
 *             anything went wrong during the communication between client
 *             and server.
 * 
 */
private String sendRequest(String body) throws IOException {

    BufferedReader reader = null;
    OutputStreamWriter writer = null;

    try {

        // create the URL object from the endpoint
        URL url = new URL(API_ENDPOINT);

        // open the connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // use POST and configure the connection
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // set the request headers
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("X-Api-Token", apiToken);
        connection.setRequestProperty("X-Version", "" + apiVersion);
        connection.setRequestProperty("Content-Length", String.valueOf(body.length()));

        // construct the writer and write request
        writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(body);
        writer.flush();

        // listen on the server response
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        // construct the server response and return
        StringBuilder sb = new StringBuilder();
        for (String line; (line = reader.readLine()) != null;) {
            sb.append(line);
        }

        // return the result
        return sb.toString();

    } catch (MalformedURLException e) {
        // the URL we specified as endpoint was not valid
        System.err.println("The URL " + API_ENDPOINT + " is not a valid URL");
        e.printStackTrace();
        return null;
    } catch (ProtocolException e) {
        // this should not happen, it means that we specified a wrong
        // protocol
        System.err.println("The HTTP method is not valid. Please check if you specified POST.");
        e.printStackTrace();
        return null;
    } finally {
        // close the reader and writer
        try {
            writer.close();
        } catch (Exception e) {
            // intentionally left blank
        }
        try {
            reader.close();
        } catch (Exception e) {
            // intentionally left blank
        }
    }
}

From source file:org.dcm4che3.tool.wadors.WadoRS.java

private static SimpleHTTPResponse sendRequest(final WadoRS main) throws IOException {
    URL newUrl = new URL(main.getUrl());

    LOG.info("WADO-RS URL: {}", newUrl);

    HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection();

    connection.setDoOutput(true);//from  www  .j a  va2  s. co  m

    connection.setDoInput(true);

    connection.setInstanceFollowRedirects(false);

    connection.setRequestMethod("GET");

    connection.setRequestProperty("charset", "utf-8");

    String[] acceptHeaders = compileAcceptHeader(main.acceptTypes);

    LOG.info("Accept-Headers: {}", Arrays.toString(acceptHeaders));

    for (String acceptStr : acceptHeaders)
        connection.addRequestProperty("Accept", acceptStr);

    if (main.getRequestTimeOut() != null) {
        connection.setConnectTimeout(Integer.valueOf(main.getRequestTimeOut()));
        connection.setReadTimeout(Integer.valueOf(main.getRequestTimeOut()));
    }

    connection.setUseCaches(false);

    int responseCode = connection.getResponseCode();
    String responseMessage = connection.getResponseMessage();

    boolean isErrorCase = responseCode >= HttpURLConnection.HTTP_BAD_REQUEST;
    if (!isErrorCase) {

        InputStream in = null;
        if (connection.getHeaderField("content-type").contains("application/json")
                || connection.getHeaderField("content-type").contains("application/zip")) {
            String headerPath;
            in = connection.getInputStream();
            if (main.dumpHeader)
                headerPath = writeHeader(connection.getHeaderFields(),
                        new File(main.outDir, "out.json" + "-head"));
            else {
                headerPath = connection.getHeaderField("content-location");
            }
            File f = new File(main.outDir,
                    connection.getHeaderField("content-type").contains("application/json") ? "out.json"
                            : "out.zip");
            Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
            main.retrievedInstances.put(headerPath, f.toPath().toAbsolutePath());
        } else {
            if (main.dumpHeader)
                dumpHeader(main, connection.getHeaderFields());
            in = connection.getInputStream();
            try {
                File spool = new File(main.outDir, "Spool");
                Files.copy(in, spool.toPath(), StandardCopyOption.REPLACE_EXISTING);
                String boundary;
                BufferedReader rdr = new BufferedReader(new InputStreamReader(new FileInputStream(spool)));
                boundary = (rdr.readLine());
                boundary = boundary.substring(2, boundary.length());
                rdr.close();
                FileInputStream fin = new FileInputStream(spool);
                new MultipartParser(boundary).parse(fin, new MultipartParser.Handler() {

                    @Override
                    public void bodyPart(int partNumber, MultipartInputStream partIn) throws IOException {

                        Map<String, List<String>> headerParams = partIn.readHeaderParams();
                        String mediaType;
                        String contentType = headerParams.get("content-type").get(0);

                        if (contentType.contains("transfer-syntax"))
                            mediaType = contentType.split(";")[0];
                        else
                            mediaType = contentType;

                        // choose writer
                        if (main.isMetadata) {
                            main.writerType = ResponseWriter.XML;

                        } else {
                            if (mediaType.equalsIgnoreCase("application/dicom")) {
                                main.writerType = ResponseWriter.DICOM;
                            } else if (isBulkMediaType(mediaType)) {
                                main.writerType = ResponseWriter.BULK;
                            } else {
                                throw new IllegalArgumentException("Unknown media type "
                                        + "returned by server, media type = " + mediaType);
                            }

                        }
                        try {
                            main.writerType.readBody(main, partIn, headerParams);
                        } catch (Exception e) {
                            System.out.println("Error parsing media type to determine extension" + e);
                        }
                    }

                    private boolean isBulkMediaType(String mediaType) {
                        if (mediaType.contains("octet-stream"))
                            return true;
                        for (Field field : MediaTypes.class.getFields()) {
                            try {
                                if (field.getType().equals(String.class)) {
                                    String tmp = (String) field.get(field);
                                    if (tmp.equalsIgnoreCase(mediaType))
                                        return true;
                                }
                            } catch (Exception e) {
                                System.out.println("Error deciding media type " + e);
                            }
                        }

                        return false;
                    }
                });
                fin.close();
                spool.delete();
            } catch (Exception e) {
                System.out.println("Error parsing Server response - " + e);
            }
        }

    } else {
        LOG.error("Server returned {} - {}", responseCode, responseMessage);
    }

    connection.disconnect();

    main.response = new WadoRSResponse(responseCode, responseMessage, main.retrievedInstances);
    return new SimpleHTTPResponse(responseCode, responseMessage);

}

From source file:com.online.fullsail.SaveWebMedia.java

@Override
protected File doInBackground(String... paths) {
    String exportfile = paths[0].substring(paths[0].lastIndexOf('/') + 1, paths[0].length());
    String vDownload = externalData + "/" + exportfile;
    File downFile = null;//w  ww.j  a  v a2s . c  o m
    try {
        // set the download URL of the file to be downloaded
        URL url = new URL(paths[0]);

        // create the new connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("Connection", "Keep-Alive");

        // and connect!
        urlConnection.connect();

        // set the path where we want to save the file
        File SDCardRoot = Environment.getExternalStorageDirectory();
        // create a new file, with specified path and name
        downFile = new File(SDCardRoot, vDownload);

        // this will be used to write the downloaded data
        // into the file
        // we created
        FileOutputStream fileOutput = new FileOutputStream(downFile);

        // this will be used in reading the data from the
        // internet
        InputStream inputStream = urlConnection.getInputStream();

        // this is the total size of the file
        int totalSize = urlConnection.getContentLength();
        // variable to store total downloaded bytes
        int downloadedSize = 0;

        // create a buffer...
        byte[] buffer = new byte[1024];
        int bufferLength = 0;
        // used to store a temporary buffer then
        // read through the input buffer and write
        // to the specified output file
        int priorProgress = 0;
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            downloadedSize += bufferLength;
            int currentSize = (int) (downloadedSize * 100 / totalSize);
            if (currentSize > priorProgress) {
                priorProgress = (int) (downloadedSize * 100 / totalSize);
                publishProgress(currentSize);
            }
            fileOutput.write(buffer, 0, bufferLength);
        }
        // close the output stream when done
        fileOutput.close();
        inputStream.close();

        // catch some possible errors...
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return downFile;
    // When finished, return the resulting file
}

From source file:com.mercandalli.android.apps.files.common.net.TaskGet.java

@Override
protected String doInBackground(Void... urls) {
    try {/*w  w w  . jav a2 s  .c  o  m*/
        if (this.parameters != null) {
            if (!StringUtils.isNullOrEmpty(Config.getNotificationId())) {
                parameters.add(new StringPair("android_id", "" + Config.getNotificationId()));
            }
            url = NetUtils.addUrlParameters(url, parameters);
        }

        Log.d("TaskGet", "url = " + url);

        URL tmp_url = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) tmp_url.openConnection();
        conn.setReadTimeout(10_000);
        conn.setConnectTimeout(15_000);
        conn.setRequestMethod("GET");
        if (isAuthentication) {
            conn.setRequestProperty("Authorization", "Basic " + Config.getUserToken());
        }
        conn.setUseCaches(false);
        conn.setDoInput(true);

        conn.connect(); // Starts the query
        int responseCode = conn.getResponseCode();
        InputStream inputStream = new BufferedInputStream(conn.getInputStream());

        // convert inputstream to string
        String resultString = convertInputStreamToString(inputStream);

        //int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode >= 300) {
            resultString = "Status Code " + responseCode + ". " + resultString;
        }

        conn.disconnect();

        return resultString;
    } catch (IOException e) {
        Log.e(getClass().getName(), "IOException", e);
    }
    return null;
}

From source file:TaxSvc.TaxSvc.java

public CancelTaxResult CancelTax(CancelTaxRequest req) {

    //Create URL//w w w . j  a  v a 2s. co  m
    String taxget = svcURL + "/1.0/tax/cancel";
    URL url;
    HttpURLConnection conn;
    try {
        //Connect to URL with authorization header, request content.
        url = new URL(taxget);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null
        String content = mapper.writeValueAsString(req);
        //System.out.println(content);         //Uncomment to see the content of the request object
        conn.setRequestProperty("Content-Length", Integer.toString(content.length()));

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

        conn.disconnect();

        if (conn.getResponseCode() != 200) //Note: tax/cancel will return a 200 response even if the document could not be cancelled. Special attention needs to be paid to the ResultCode.
        { //If we got a more serious error, print out the error message.
            CancelTaxResult res = mapper.readValue(conn.getErrorStream(), CancelTaxResult.class); //Deserialize response
            return res;
        } else {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            CancelTaxResponse res = mapper.readValue(conn.getInputStream(), CancelTaxResponse.class); //Deserialize response
            return res.CancelTaxResult;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:foam.starwisp.NetworkManager.java

public List<String> PostFile(String requestURL, File uploadFile) throws IOException {

    // creates a unique boundary based on time stamp
    String boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);//from   www.j  a v a  2  s .  c  o m
    httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
    httpConn.setRequestProperty("Test", "Bonjour");
    OutputStream outputStream = httpConn.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);

    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"binary\";" + "filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();

    List<String> response = new ArrayList<String>();

    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }

    return response;
}