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:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Send a file via HTTP POST with basic authentication.
 * //from   w w w .  j  a va2  s .com
 * @param urlStr the server url to POST to.
 * @param file the file to send.
 * @param user the user or <code>null</code>.
 * @param password the password or <code>null</code>.
 * @return the return string from the POST.
 * @throws Exception
 */
public static String sendFilePost(String urlStr, File file, String user, String password) throws Exception {
    BufferedOutputStream wr = null;
    FileInputStream fis = null;
    HttpURLConnection conn = null;
    try {
        fis = new FileInputStream(file);
        long fileSize = file.length();
        // Authenticator.setDefault(new Authenticator(){
        // protected PasswordAuthentication getPasswordAuthentication() {
        // return new PasswordAuthentication("test", "test".toCharArray());
        // }
        // });
        conn = makeNewConnection(urlStr);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // conn.setChunkedStreamingMode(0);
        conn.setUseCaches(true);

        // conn.setRequestProperty("Accept-Encoding", "gzip ");
        // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Type", "application/x-zip-compressed");
        // conn.setRequestProperty("Content-Length", "" + fileSize);
        // conn.setRequestProperty("Connection", "Keep-Alive");

        if (user != null && password != null) {
            conn.setRequestProperty("Authorization", getB64Auth(user, password));
        }
        conn.connect();

        wr = new BufferedOutputStream(conn.getOutputStream());
        long bufferSize = Math.min(fileSize, maxBufferSize);

        if (GPLog.LOG)
            GPLog.addLogEntry(TAG, "BUFFER USED: " + bufferSize);
        byte[] buffer = new byte[(int) bufferSize];
        int bytesRead = fis.read(buffer, 0, (int) bufferSize);
        long totalBytesWritten = 0;
        while (bytesRead > 0) {
            wr.write(buffer, 0, (int) bufferSize);
            totalBytesWritten = totalBytesWritten + bufferSize;
            if (totalBytesWritten >= fileSize)
                break;

            bufferSize = Math.min(fileSize - totalBytesWritten, maxBufferSize);
            bytesRead = fis.read(buffer, 0, (int) bufferSize);
        }
        wr.flush();

        String responseMessage = conn.getResponseMessage();

        if (GPLog.LOG)
            GPLog.addLogEntry(TAG, "POST RESPONSE: " + responseMessage);
        return responseMessage;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (wr != null)
            wr.close();
        if (fis != null)
            fis.close();
        if (conn != null)
            conn.disconnect();
    }
}

From source file:org.csware.ee.utils.Tools.java

public static String reqByPost(String path) {
    String info = "";
    try {/*from w ww.j  a v  a  2s . c om*/
        // URL
        URL url = new URL(path);
        // HttpURLConnection
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        // ?Input?output?Cache
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        /** ?method=post */
        urlConn.setRequestMethod("POST");
        urlConn.setRequestProperty("Connection", "Keep-Alive");
        urlConn.setRequestProperty("Charset", "utf-8");
        InputStream in = urlConn.getInputStream();

        try {

            byte[] buffer = new byte[65536];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int readLength = in.read(buffer);
            long totalLength = 0;
            while (readLength >= 0) {
                bos.write(buffer, 0, readLength);
                totalLength = totalLength + readLength;
                readLength = in.read(buffer);

            }
            info = bos.toString();

        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
        // 
        urlConn.setConnectTimeout(5 * 1000);
        // 
        urlConn.connect();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
    return info.replaceAll("\r\n", " ");
}

From source file:com.hippo.httpclient.JsonPoster.java

@Override
public void onBeforeConnect(HttpURLConnection conn) throws Exception {
    super.onBeforeConnect(conn);

    conn.setDoOutput(true);/*  w w  w . j a  v  a2 s .c om*/
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
}

From source file:org.exoplatform.utils.image.CookieAwarePicassoDownloader.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.setUseCaches(true);

    int responseCode = connection.getResponseCode();
    if (responseCode >= 300) {
        connection.disconnect();/*w ww .j  a  v  a 2  s. co  m*/
        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:gov.nasa.arc.geocam.geocam.HttpPost.java

public static HttpURLConnection createConnection(String url, String username, String password)
        throws IOException {
    boolean useAuth = !password.equals("");
    // force SSL if useAuth=true (would send password unencrypted otherwise)
    boolean useSSL = useAuth || url.startsWith("https");

    Log.d("HttpPost", "password: " + password);
    Log.d("HttpPost", "useSSL: " + useSSL);

    if (useSSL) {
        if (!url.startsWith("https")) {
            // replace http: with https: -- this will obviously screw
            // up if input is something other than http so don't do that :)
            url = "https:" + url.substring(5);
        }/*  w ww.  j a  va2s.  c o  m*/

        // would rather not do this, need to check if there's still a problem
        // with our ssl certificates on NASA servers.
        try {
            DisableSSLCertificateCheckUtil.disableChecks();
        } catch (GeneralSecurityException e) {
            throw new IOException("HttpPost - disable ssl: " + e);
        }
    }

    HttpURLConnection conn;
    try {
        if (useSSL) {
            conn = (HttpsURLConnection) (new URL(url)).openConnection();
        } else {
            conn = (HttpURLConnection) (new URL(url)).openConnection();
        }
    } catch (IOException e) {
        throw new IOException("HttpPost - IOException: " + e);
    }

    if (useAuth) {
        // add pre-emptive http basic authentication.  using
        // homebrew version -- early versions of android
        // authenticator have problems and this is easy.
        String userpassword = username + ":" + password;
        String encodedAuthorization = Base64.encode(userpassword.getBytes());
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
    }

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

    return conn;
}

From source file:br.bireme.tb.URLS.java

/**
 * Given an url, loads its content (POST - method)
 * @param url url to be loaded//from   w ww .j  av a2s.  co m
 * @param urlParameters post parameters
 * @return an array with the real location of the page (in case of redirect)
 * and its content.
 * @throws IOException
 */
public static String[] loadPagePost(final URL url, final String urlParameters) throws IOException {
    if (url == null) {
        throw new NullPointerException("url");
    }
    if (urlParameters == null) {
        throw new NullPointerException("urlParameters");
    }
    final String encodedParams = URLEncoder.encode(urlParameters, DEFAULT_ENCODING);
    //System.out.print("loading page (POST): [" + url + "] params: " + urlParameters);

    //Create connection
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("Content-Length", "" + Integer.toString(encodedParams.getBytes().length));
    //.getBytes(DEFAULT_ENCODING).length));
    connection.setRequestProperty("Content-Language", "pt-BR");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
        wr.write(encodedParams.getBytes(DEFAULT_ENCODING));
        //wr.writeBytes(urlParameters);
        wr.flush();
    }

    //Get Response
    final StringBuffer response = new StringBuffer();
    try (final BufferedReader rd = new BufferedReader(
            new InputStreamReader(connection.getInputStream(), DEFAULT_ENCODING))) {
        while (true) {
            final String line = rd.readLine();
            if (line == null) {
                break;
            }
            response.append(line);
            response.append('\n');
        }
    }
    connection.disconnect();

    return new String[] { url.toString() + "?" + urlParameters, response.toString() };
}

From source file:net.technicpack.minecraftcore.mojang.auth.AuthenticationService.java

private String postJson(String url, String data) throws IOException {
    byte[] rawData = data.getBytes("UTF-8");
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setUseCaches(false);
    connection.setDoOutput(true);/*from  w  ww .  j  a v a  2 s. c  o  m*/
    connection.setDoInput(true);
    connection.setConnectTimeout(15000);
    connection.setReadTimeout(15000);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    connection.setRequestProperty("Content-Length", rawData.length + "");
    connection.setRequestProperty("Content-Language", "en-US");

    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
    writer.write(rawData);
    writer.flush();
    writer.close();

    InputStream stream = null;
    String returnable = null;
    try {
        stream = connection.getInputStream();
        returnable = IOUtils.toString(stream, Charsets.UTF_8);
    } catch (IOException e) {
        stream = connection.getErrorStream();

        if (stream == null) {
            throw e;
        }
    } finally {
        try {
            if (stream != null)
                stream.close();
        } catch (IOException e) {
        }
    }

    return returnable;
}

From source file:org.dcm4che3.tool.qc.QC.java

private static QCResult sendRequest(String desc, QC qc, Object qcMessage) {

    HttpURLConnection connection = null;
    String bfr = "";
    QCResult result = null;//  w w  w  .j  a va  2s.com
    try {
        URL url = new URL(qc.getUrl());
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);

        connection.setDoInput(true);

        connection.setInstanceFollowRedirects(false);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("charset", "utf-8");

        connection.setRequestProperty("Accept", "application/json");

        connection.setUseCaches(false);

        writeMessage(connection, (JsonStructure) qcMessage);

        InputStream in = connection.getInputStream();

        BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
        while (rdr.ready())
            bfr += rdr.readLine();
        result = new QCResult(desc, bfr, connection.getResponseCode());
        return result;
    } catch (Exception e) {
        System.out.println("Error preparing request or " + "parsing Server response - " + e);
    }
    connection.disconnect();
    return result;
}

From source file:org.wisdom.openid.connect.request.UserInfoRequest.java

public UserInfoResponse execute() throws IOException {

    HttpURLConnection connection = (HttpURLConnection) userInfoEndpoint.openConnection();
    connection.addRequestProperty("Authorization", format("Bearer %s", accessToken));

    connection.setUseCaches(false);
    connection.setDoInput(true);//from www  .ja  v  a  2 s. c  om
    connection.setDoOutput(true);

    //Get Response
    JsonNode node = new ObjectMapper().readTree(connection.getInputStream());
    return new UserInfoResponse(node.get("sub").asText(), node);

}

From source file:com.juick.android.Utils.java

public static int doHttpGetRequest(String url) {
    try {/*from www .j  a  v a 2s .c  o  m*/
        HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
        conn.setUseCaches(false);
        conn.connect();
        int status = conn.getResponseCode();
        conn.disconnect();
        return status;
    } catch (Exception e) {
        Log.e("doHttpGetRequest", e.toString());
    }
    return 0;
}