Example usage for java.net HttpURLConnection HTTP_NOT_MODIFIED

List of usage examples for java.net HttpURLConnection HTTP_NOT_MODIFIED

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_NOT_MODIFIED.

Prototype

int HTTP_NOT_MODIFIED

To view the source code for java.net HttpURLConnection HTTP_NOT_MODIFIED.

Click Source Link

Document

HTTP Status-Code 304: Not Modified.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection con = (HttpURLConnection) new URL("http://www.google.coom").openConnection();
    con.setRequestMethod("HEAD");
    System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED);
}

From source file:org.apache.myfaces.custom.skin.webapp.CachingStyleSheetLoader.java

/**
 * Loads the stylesheet only if the file has been modified or
 * the cache has expired./* www . ja v a 2  s .  com*/
 */
public void loadStyleSheet(HttpServletRequest req, HttpServletResponse resp, ServletConfig config)
        throws IOException {
    File file = getFile(req, config);
    if (file != null && file.exists()) {
        if (isFileModified(file, req)) {
            long lastModified = file.lastModified();
            defineCaching(req, resp, lastModified);
            writeFile(file, resp);
        } else {
            resp.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED);
            return;
        }
    } else {
        String requestURI = req.getRequestURI();
        String filename = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        log.error("The resource " + filename + " was not found.");

        resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND, filename);
        return;
    }
}

From source file:org.sonar.server.platform.ws.L10nWs.java

protected void serializeMessages(Request request, Response response) throws IOException {
    Date timestamp = request.paramAsDateTime("ts");
    if (timestamp != null && timestamp.after(server.getStartedAt())) {
        response.stream().setStatus(HttpURLConnection.HTTP_NOT_MODIFIED).output().close();
    } else {/*  w ww  . j  av a2s  . c o  m*/

        Locale locale = userSession.locale();
        String localeParam = request.param("locale");
        if (localeParam != null) {
            locale = LocaleUtils.toLocale(localeParam);
        }
        JsonWriter json = response.newJsonWriter().beginObject();
        for (String messageKey : i18n.getPropertyKeys()) {
            json.prop(messageKey, i18n.message(locale, messageKey, messageKey));
        }
        json.endObject().close();
    }
}

From source file:com.aitangba.volley.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {/*from w w  w .ja v a  2  s.c o m*/
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            int statusCode = httpResponse.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpURLConnection.HTTP_NOT_MODIFIED) {

                Cache.Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED, null, responseHeaders, true,
                            SystemClock.elapsedRealtime() - requestStart);
                }

                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED, entry.data,
                        entry.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
            }

            // Handle moved resources
            if (statusCode == HttpURLConnection.HTTP_MOVED_PERM
                    || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                String newUrl = responseHeaders.get("Location");
                request.setRedirectUrl(newUrl);
            }

            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }

            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, httpResponse.getStatusCode());

            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                    SystemClock.elapsedRealtime() - requestStart);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            if (statusCode == HttpURLConnection.HTTP_MOVED_PERM
                    || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(),
                        request.getUrl());
            } else {
                VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            }
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                        SystemClock.elapsedRealtime() - requestStart);
                if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED
                        || statusCode == HttpURLConnection.HTTP_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else if (statusCode == HttpURLConnection.HTTP_MOVED_PERM
                        || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                    attemptRetryOnException("redirect", request, new RedirectError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(e);
            }
        }
    }
}

From source file:eionet.cr.util.URLUtil.java

/**
 * Connect to the URL and check if it is modified since the timestamp argument. Returns null, if it cannot be determined for
 * sure.// w  w  w.j a v a2  s  .c  o  m
 *
 * @param urlString
 * @param timestamp
 * @return true if it is modified.
 */
public static Boolean isModifiedSince(String urlString, long timestamp) {

    if (!URLUtil.isURL(urlString)) {
        return Boolean.FALSE;
    }

    if (timestamp == 0) {
        return Boolean.TRUE;
    }

    URLConnection urlConnection = null;
    try {
        URL url = new URL(StringUtils.substringBefore(urlString, "#"));
        urlConnection = escapeIRI(url).openConnection();
        urlConnection.setRequestProperty("Connection", "close");
        urlConnection.setRequestProperty("User-Agent", userAgentHeader());
        urlConnection.setIfModifiedSince(timestamp);

        int responseCode = ((HttpURLConnection) urlConnection).getResponseCode();
        System.out.println(responseCode);
        if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return Boolean.FALSE;
        } else if (responseCode == HttpURLConnection.HTTP_OK) {
            return Boolean.TRUE;
        } else {
            // Return null to indicate if it's unclear whether the source has
            // been modified or not.
            return null;
        }
    } catch (IOException ioe) {
        return null;
    } finally {
        URLUtil.disconnect(urlConnection);
    }
}

From source file:net.sf.ehcache.constructs.web.filter.GzipFilterTest.java

/**
 * A 0 length body should give a 0 length gzip body and content length
 * <p/>//  ww w .  j a  v  a 2s  . c o  m
 * Manual test: wget -d --server-response --timestamping --header='If-modified-Since: Fri, 13 May 3006 23:54:18 GMT' --header='Accept-Encoding: gzip' http://localhost:9080/empty_gzip/empty.html
 */
public void testZeroLengthHTML() throws Exception {

    String url = "http://localhost:9080/empty_gzip/empty.html";
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(url);
    httpMethod.addRequestHeader("If-modified-Since", "Fri, 13 May 3006 23:54:18 GMT");
    httpMethod.addRequestHeader("Accept-Encoding", "gzip");
    int responseCode = httpClient.executeMethod(httpMethod);
    assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, responseCode);
    byte[] responseBody = httpMethod.getResponseBody();
    assertEquals(null, responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));
    checkNullOrZeroContentLength(httpMethod);
}

From source file:net.andylizi.colormotd.Updater.java

private boolean checkUpdate() {
    if (file != null && file.exists()) {
        cancel();// www .  jav a2 s  .  c  o m
    }
    URL url;
    try {
        url = new URL(UPDATE_URL);
    } catch (MalformedURLException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        return false;
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.addRequestProperty("User-Agent", userAgent);
        if (etag != null) {
            conn.addRequestProperty("If-None-Match", etag);
        }
        conn.addRequestProperty("Accept", "application/json,text/plain,*/*;charset=utf-8");
        conn.addRequestProperty("Accept-Encoding", "gzip");
        conn.addRequestProperty("Cache-Control", "no-cache");
        conn.addRequestProperty("Date", new Date().toString());
        conn.addRequestProperty("Connection", "close");

        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(2000);

        conn.connect();

        if (conn.getHeaderField("ETag") != null) {
            etag = conn.getHeaderField("ETag");
        }
        if (DEBUG) {
            logger.log(Level.INFO, "DEBUG ResponseCode: {0}", conn.getResponseCode());
            logger.log(Level.INFO, "DEBUG ETag: {0}", etag);
        }
        if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return false;
        } else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }

        BufferedReader input = null;
        if (conn.getContentEncoding() != null && conn.getContentEncoding().contains("gzip")) {
            input = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"), 1);
        } else {
            input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 1);
        }

        StringBuilder builder = new StringBuilder();
        String buffer = null;
        while ((buffer = input.readLine()) != null) {
            builder.append(buffer);
        }
        try {
            JSONObject jsonObj = (JSONObject) new JSONParser().parse(builder.toString());
            int build = ((Number) jsonObj.get("build")).intValue();
            if (build <= ColorMOTD.buildVersion) {
                return false;
            }
            String version = (String) jsonObj.get("version");
            String msg = (String) jsonObj.get("msg");
            String download_url = (String) jsonObj.get("url");
            newVersion = new NewVersion(version, build, msg, download_url);
            return true;
        } catch (ParseException ex) {
            if (DEBUG) {
                ex.printStackTrace();
            }
            exception = ex;
            return false;
        }
    } catch (SocketTimeoutException ex) {
        return false;
    } catch (IOException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        exception = ex;
        return false;
    }
}

From source file:com.supremainc.biostar2.sdk.volley.toolbox.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = new HashMap<String, String>();
        try {//from www  .  jav  a2  s.co  m
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
                return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED,
                        request.getCacheEntry() == null ? null : request.getCacheEntry().data, responseHeaders,
                        true);
            }

            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }

            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);

            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
        } catch (SocketTimeoutException e) {
            if (ConfigDataProvider.DEBUG) {
                Log.e("Volley", "SocketTimeoutException");
            }
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            if (ConfigDataProvider.DEBUG) {
                Log.e("Volley", "ConnectTimeoutException");
            }
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            if (ConfigDataProvider.DEBUG) {
                Log.e("Volley", "MalformedURLException");
            }
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                Log.e("Connection Error", " " + e.getMessage());
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (ConfigDataProvider.DEBUG) {
                Log.e("Volley", "IOException statusCode:" + statusCode + " url:" + request.getUrl());
            }
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false);
                if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}

From source file:net.andylizi.colormotd.anim.updater.Updater.java

private boolean checkUpdate() {
    if (new File(Bukkit.getUpdateFolderFile(), fileName).exists()) {
        cancel();//from  ww w.  ja  v  a  2s .  c o  m
    }
    URL url;
    try {
        url = new URL(UPDATE_URL);
    } catch (MalformedURLException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        return false;
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.addRequestProperty("User-Agent", USER_AGENT);
        if (etag != null) {
            conn.addRequestProperty("If-None-Match", etag);
        }
        conn.addRequestProperty("Accept", "application/json,text/plain,*/*;charset=utf-8");
        conn.addRequestProperty("Accept-Encoding", "gzip");
        conn.addRequestProperty("Cache-Control", "no-cache");
        conn.addRequestProperty("Date", new Date().toString());
        conn.addRequestProperty("Connection", "close");

        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(2000);

        conn.connect();

        if (conn.getHeaderField("ETag") != null) {
            etag = conn.getHeaderField("ETag");
        }
        if (DEBUG) {
            logger.log(Level.INFO, "DEBUG ResponseCode: {0}", conn.getResponseCode());
            logger.log(Level.INFO, "DEBUG ETag: {0}", etag);
        }
        if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return false;
        } else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }

        BufferedReader input = null;
        if (conn.getContentEncoding() != null && conn.getContentEncoding().contains("gzip")) {
            input = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"), 1);
        } else {
            input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 1);
        }

        StringBuilder builder = new StringBuilder();
        String buffer = null;
        while ((buffer = input.readLine()) != null) {
            builder.append(buffer);
        }
        try {
            JSONObject jsonObj = (JSONObject) new JSONParser().parse(builder.toString());
            int build = ((Number) jsonObj.get("build")).intValue();
            if (build <= buildVersion) {
                return false;
            }
            String version = (String) jsonObj.get("version");
            String msg = (String) jsonObj.get("msg");
            String download_url = (String) jsonObj.get("url");
            newVersion = new NewVersion(version, build, msg, download_url);
            return true;
        } catch (ParseException ex) {
            if (DEBUG) {
                ex.printStackTrace();
            }
            exception = ex;
            return false;
        }
    } catch (SocketTimeoutException ex) {
        return false;
    } catch (IOException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        exception = ex;
        return false;
    }
}

From source file:com.exzogeni.dk.http.HttpTask.java

@Override
public V call() throws Exception {
    final long startTime = SystemClock.uptimeMillis();
    try {//from ww w . ja  v  a  2s .com
        final URI uri = getEncodedUriInternal();
        if (mCachePolicy == null || mCachePolicy.shouldCache(uri)) {
            final CacheManager cm = mHttpManager.getCacheManager();
            final Map<String, List<String>> headers = new HashMap<>();
            final InputStream content = cm.get(uri, headers);
            if (content != null) {
                return onSuccessInternal(HttpURLConnection.HTTP_NOT_MODIFIED,
                        Collections.<String, List<String>>emptyMap(), content);
            } else {
                mHeaders.putAll(headers);
            }
        }
        return onPerformNetworkRequest(uri);
    } finally {
        mHttpManager.log(this, (SystemClock.uptimeMillis() - startTime),
                HttpStatus.getStatusLine(mStatusCode.get()));
    }
}