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.nkc.nkcpost.helper.HttpRequest.java

/**
 * Post the request//from w  w  w.ja  v  a 2  s  . co 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();
}

From source file:com.google.plus.samples.photohunt.tasks.FetchJsonTaskLoader.java

protected T fetchData() throws IOException {
    HttpURLConnection urlConnection = null;

    try {//w w w  .  j a v a  2 s. c  om
        URL url = new URL(mUrl);

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setUseCaches(true);
        urlConnection.setRequestMethod("GET");

        AuthUtil.setAuthHeaders(urlConnection);

        return onPostFetch(HttpUtils.getContent(urlConnection.getInputStream()));
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.cpjd.roblu.bluealliance.BLUE.java

/**
 * Makes an API call to The Blue Alliance.
 * // ww  w.j  a va 2  s  . c  om
 * @param apiReq The REST endpoint to make a request to.
 * @return The parsed JSON data.
 */
public static Object api(String apiReq) throws BLUEApiException {
    if (!isInitialized())
        throw new BLUEApiException("BLUE was not initialized.", null);

    String endpoint = API_BASE + apiReq;

    URL endpointUrl;

    try {
        endpointUrl = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new BLUEApiException("Malformed API request.", e);
    }

    HttpURLConnection conn;

    try {
        conn = (HttpURLConnection) endpointUrl.openConnection();
    } catch (IOException e) {
        throw new BLUEApiException("Could not open connection.", e);
    }

    try {
        conn.setRequestMethod("GET");
    } catch (ProtocolException e) {
        throw new BLUEApiException("Could not set the request type.", e);
    }

    conn.setRequestProperty("X-TBA-App-Id", X_TBA_APP_ID);
    conn.setUseCaches(false);

    InputStream is;
    BufferedReader reader;

    try {
        is = conn.getInputStream();
        reader = new BufferedReader(new InputStreamReader(is));
    } catch (IOException e) {
        throw new BLUEApiException("Fatal! No internet!", e);
    }

    String jsonString = "";
    String respLine = "";

    try {
        while ((respLine = reader.readLine()) != null) {
            jsonString += respLine;
        }

        reader.close();
    } catch (IOException e) {
        throw new BLUEApiException("Error reading the response.", e);
    }

    Object obj;

    try {
        obj = parser.parse(jsonString);
    } catch (ParseException e) {
        throw new BLUEApiException("Malformed response received.", e);
    }

    return obj;
}

From source file:com.mobile.natal.natalchart.NetworkUtilities.java

/**
 * Send a file via HTTP POST with basic authentication.
 *
 * @param context  the context to use.//ww w .  ja  v a2s.c  om
 * @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 if something goes wrong.
 */
public static String sendFilePost(Context context, 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());
        // }
        // });
        urlStr = urlStr + "?name=" + file.getName();
        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/octet-stream");
        // conn.setRequestProperty("Content-Length", "" + fileSize);
        // conn.setRequestProperty("Connection", "Keep-Alive");

        if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) {
            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();

        int responseCode = conn.getResponseCode();
        return getMessageForCode(context, responseCode,
                context.getResources().getString(R.string.file_upload_completed_properly));

    } catch (Exception e) {
        throw e;
    } finally {
        if (wr != null)
            wr.close();
        if (fis != null)
            fis.close();
        if (conn != null)
            conn.disconnect();
    }
}

From source file:com.docdoku.cli.helpers.FileHelper.java

private void performHeadHTTPMethod(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(true);/*  w w w. j  a va 2 s . co m*/
    conn.setRequestProperty("Connection", "Keep-Alive");
    byte[] encoded = Base64.encodeBase64((login + ":" + password).getBytes("ISO-8859-1"));
    conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));
    conn.setRequestMethod("HEAD");
    conn.connect();
    int code = conn.getResponseCode();
}

From source file:org.apache.axis.utils.XMLUtils.java

/**
 * Utility to get the bytes at a protected uri
 *
 * This will retrieve the URL if a username and password are provided.
 * The java.net.URL class does not do Basic Authentication, so we have to
 * do it manually in this routine.//from ww w  . ja v a 2  s. c  om
 *
 * If no username is provided, we create an InputSource from the uri
 * and let the InputSource go fetch the contents.
 *
 * @param uri the resource to get
 * @param username basic auth username
 * @param password basic auth password
 */
private static InputSource getInputSourceFromURI(String uri, String username, String password)
        throws IOException, ProtocolException, UnsupportedEncodingException {
    URL wsdlurl = null;
    try {
        wsdlurl = new URL(uri);
    } catch (MalformedURLException e) {
        // we can't process it, it might be a 'simple' foo.wsdl
        // let InputSource deal with it
        return new InputSource(uri);
    }

    // if no authentication, just let InputSource deal with it
    if (username == null && wsdlurl.getUserInfo() == null) {
        return new InputSource(uri);
    }

    // if this is not an HTTP{S} url, let InputSource deal with it
    if (!wsdlurl.getProtocol().startsWith("http")) {
        return new InputSource(uri);
    }

    URLConnection connection = wsdlurl.openConnection();
    // Does this work for https???
    if (!(connection instanceof HttpURLConnection)) {
        // can't do http with this URL, let InputSource deal with it
        return new InputSource(uri);
    }
    HttpURLConnection uconn = (HttpURLConnection) connection;
    String userinfo = wsdlurl.getUserInfo();
    uconn.setRequestMethod("GET");
    uconn.setAllowUserInteraction(false);
    uconn.setDefaultUseCaches(false);
    uconn.setDoInput(true);
    uconn.setDoOutput(false);
    uconn.setInstanceFollowRedirects(true);
    uconn.setUseCaches(false);

    // username/password info in the URL overrides passed in values
    String auth = null;
    if (userinfo != null) {
        auth = userinfo;
    } else if (username != null) {
        auth = (password == null) ? username : username + ":" + password;
    }

    if (auth != null) {
        uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(httpAuthCharEncoding)));
    }

    uconn.connect();

    return new InputSource(uconn.getInputStream());
}

From source file:org.dcm4che3.tool.qidors.QidoRS.java

private static String sendRequest(URL url, final QidoRS main) throws IOException {

    LOG.info("URL: {}", url);

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

    connection.setDoOutput(true);//from ww  w  .  j  ava  2  s .c om

    connection.setDoInput(true);

    connection.setInstanceFollowRedirects(false);

    connection.setRequestMethod("GET");

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

    if (main.isJSON) {
        connection.setRequestProperty("Accept", "application/json");
    }

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

    connection.setUseCaches(false);

    String response = "Server responded with " + connection.getResponseCode() + " - "
            + connection.getResponseMessage();

    InputStream in = connection.getInputStream();
    try {
        main.parserType.readBody(main, in);
    } catch (Exception e) {
        System.out.println("Error parsing Server response - " + e);
    }
    connection.disconnect();

    return response;

}

From source file:cz.vutbr.fit.xzelin15.dp.consumer.WSDynamicClientFactory.java

private String transferWSDL(String wsdlURL, String userPassword, WiseProperties wiseProperties)
        throws WiseConnectionException {
    String filePath = null;/*from  www .  j a  v a 2 s . co m*/
    try {
        URL endpoint = new URL(wsdlURL);
        // Create the connection
        HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection();
        conn.setDoOutput(false);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept",
                "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
        // set Connection close, otherwise we get a keep-alive
        // connection
        // that gives us fragmented answers.
        conn.setRequestProperty("Connection", "close");
        // BASIC AUTH
        if (userPassword != null) {
            conn.setRequestProperty("Authorization",
                    "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes()));
        }
        // Read response
        InputStream is = null;
        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
        } else {
            is = conn.getErrorStream();
            InputStreamReader isr = new InputStreamReader(is);
            StringWriter sw = new StringWriter();
            char[] buf = new char[200];
            int read = 0;
            while (read != -1) {
                read = isr.read(buf);
                sw.write(buf);
            }
            throw new WiseConnectionException("Remote server's response is an error: " + sw.toString());
        }
        // saving file
        File file = new File(wiseProperties.getProperty("wise.tmpDir"),
                new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString());
        OutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
        IOUtils.copyStream(fos, is);
        fos.close();
        is.close();
        filePath = file.getPath();
    } catch (WiseConnectionException wce) {
        throw wce;
    } catch (Exception e) {
        throw new WiseConnectionException("Wsdl download failed!", e);
    }
    return filePath;
}

From source file:org.apache.jk.status.JkStatusAccessor.java

/**
 * Create a auth http connection for this url
 * /*from  www  .j av  a2s .  c  o  m*/
 * @param url
 * @param username
 * @param password
 * @return HttpConnection
 * @throws IOException
 * @throws MalformedURLException
 * @throws ProtocolException
 */
protected HttpURLConnection openConnection(String url, String username, String password)
        throws IOException, MalformedURLException, ProtocolException {
    URLConnection conn;
    conn = (new URL(url)).openConnection();
    HttpURLConnection hconn = (HttpURLConnection) conn;

    // Set up standard connection characteristics
    hconn.setAllowUserInteraction(false);
    hconn.setDoInput(true);
    hconn.setUseCaches(false);
    hconn.setDoOutput(false);
    hconn.setRequestMethod("GET");
    hconn.setRequestProperty("User-Agent", "JkStatus-Client/1.0");

    if (username != null && password != null) {
        setAuthHeader(hconn, username, password);
    }
    // Establish the connection with the server
    hconn.connect();
    return hconn;
}

From source file:com.weebly.opus1269.copyeverywhere.cloud.HttpRequest.java

/**
 * Post the request/*  w w w  .  j  av a2  s.  co  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 {
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "HTTP request. body: " + requestBody);
    }

    final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(requestBody.getBytes(UTF_8).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(UTF_8));
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (final IOException ignored) {
                // Ignore.
            }
        }
    }

    mResponseCode = conn.getResponseCode();

    InputStream inputStream = null;
    try {
        if (mResponseCode == 200) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }
        mResponseBody = getString(inputStream);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (final IOException ignored) {
                // Ignore.
            }
        }
    }

    if (BuildConfig.DEBUG) {
        Log.i(TAG, "HTTP response. body: " + mResponseBody);
    }

    conn.disconnect();
}