當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpURLConnection.HTTP_NOT_MODIFIED屬性代碼示例

本文整理匯總了Java中java.net.HttpURLConnection.HTTP_NOT_MODIFIED屬性的典型用法代碼示例。如果您正苦於以下問題:Java HttpURLConnection.HTTP_NOT_MODIFIED屬性的具體用法?Java HttpURLConnection.HTTP_NOT_MODIFIED怎麽用?Java HttpURLConnection.HTTP_NOT_MODIFIED使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在java.net.HttpURLConnection的用法示例。


在下文中一共展示了HttpURLConnection.HTTP_NOT_MODIFIED屬性的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: validate

/**
 * Returns true if this cached response should be used; false if the
 * network response should be used.
 */
public boolean validate(ResponseHeaders networkResponse) {
  if (networkResponse.headers.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
    return true;
  }

  // The HTTP spec says that if the network's response is older than our
  // cached response, we may return the cache's response. Like Chrome (but
  // unlike Firefox), this client prefers to return the newer response.
  if (lastModified != null
      && networkResponse.lastModified != null
      && networkResponse.lastModified.getTime() < lastModified.getTime()) {
    return true;
  }

  return false;
}
 
開發者ID:aabognah,項目名稱:LoRaWAN-Smart-Parking,代碼行數:20,代碼來源:ResponseHeaders.java

示例2: newStuff

/**
 * Methode sendet If-Modified-Since und wertet den Response Code aus.
 * Könnte false negativ sein, wenn 301 (dauerhaft umgezogen) kommt.
 *
 * @param url the url
 * @param expunge anzahl an tagen, wie alt ein neuer feed max sein darf
 * @return false, wenn HTTP_NOT_MODIFIED oder der Code nicht 200 ist
 * @throws Exception ausgelöst, wenn z.B. die url nicht stimmt
 */
public boolean newStuff(URL url, int expunge) throws Exception {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    String now = ifModifiedSinceDate(url.toString(), expunge);
    Log.d(AnotherRSS.TAG, "url: " + url.toString());
    Log.d(AnotherRSS.TAG, "If-Modified-Since: " + now);
    conn.setRequestProperty("If-Modified-Since", now);
    int responseCode = conn.getResponseCode();
    /*
    this close() removes the strictMode Error:
    Explicit termination method 'end' not called
    at com.android.okhttp.okio.GzipSource.<init>(GzipSource.java:62)
    -> getResponseCode() does not close the inputStream automatically !
     */
    conn.getInputStream().close();

    Log.d(AnotherRSS.TAG, "Response Code: " + Integer.toString(responseCode));
    if (BuildConfig.DEBUG) {
        error(Integer.toString(responseCode), "if modified since " + now);
    }
    if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
        return false;
    }
    if (responseCode != HttpURLConnection.HTTP_OK) {
        error(url.toString(), _ctx.getString(R.string.responseStrange));
        Log.e(AnotherRSS.TAG, _ctx.getString(R.string.responseStrange));
        return false;
    }
    return true;
}
 
開發者ID:no-go,項目名稱:AnotherRSS,代碼行數:38,代碼來源:Refresher.java

示例3: isResourceChanged

private boolean isResourceChanged(URLConnection urlConnection)
throws IOException {
    if(urlConnection instanceof HttpURLConnection) {
        return ((HttpURLConnection)urlConnection).getResponseCode() ==
            HttpURLConnection.HTTP_NOT_MODIFIED;
    }
    return lastModified == urlConnection.getLastModified();
}
 
開發者ID:MikaGuraN,項目名稱:HL4A,代碼行數:8,代碼來源:UrlModuleSourceProvider.java

示例4: isResourceChanged

private boolean isResourceChanged(URLConnection urlConnection) 
throws IOException {
    if(urlConnection instanceof HttpURLConnection) {
        return ((HttpURLConnection)urlConnection).getResponseCode() == 
            HttpURLConnection.HTTP_NOT_MODIFIED;
    }
    return lastModified == urlConnection.getLastModified();
}
 
開發者ID:middle2tw,項目名稱:whackpad,代碼行數:8,代碼來源:UrlModuleSourceProvider.java

示例5: openConnection

private URLConnection openConnection(URL aSource) throws IOException {

            // set up the URL connection
            URLConnection connection = aSource.openConnection();
            // modify the headers
            // NB: things like user authentication could go in here too.
            if (hasTimestamp) {
                connection.setIfModifiedSince(timestamp);
            }

            // in case the plugin manager is its own project, this can become an authenticator
            boolean isSecureProcotol = "https".equalsIgnoreCase(aSource.getProtocol());
            boolean isAuthInfoSet = !Strings.isNullOrEmpty(aSource.getUserInfo());
            if (isAuthInfoSet) {
                if (!isSecureProcotol) {
                    throw new IOException("Basic auth is only supported for HTTPS!");
                }
                String basicAuth = Base64.encodeBytes(aSource.getUserInfo().getBytes(StandardCharsets.UTF_8));
                connection.setRequestProperty("Authorization", "Basic " + basicAuth);
            }

            if (connection instanceof HttpURLConnection) {
                ((HttpURLConnection) connection).setInstanceFollowRedirects(false);
                connection.setUseCaches(true);
                connection.setConnectTimeout(5000);
            }
            connection.setRequestProperty("ES-Version", Version.CURRENT.toString());
            connection.setRequestProperty("ES-Build-Hash", Build.CURRENT.hashShort());
            connection.setRequestProperty("User-Agent", "elasticsearch-plugin-manager");

            // connect to the remote site (may take some time)
            connection.connect();

            // First check on a 301 / 302 (moved) response (HTTP only)
            if (connection instanceof HttpURLConnection) {
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                int responseCode = httpConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_MOVED_PERM ||
                        responseCode == HttpURLConnection.HTTP_MOVED_TEMP ||
                        responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
                    String newLocation = httpConnection.getHeaderField("Location");
                    URL newURL = new URL(newLocation);
                    if (!redirectionAllowed(aSource, newURL)) {
                        return null;
                    }
                    return openConnection(newURL);
                }
                // next test for a 304 result (HTTP only)
                long lastModified = httpConnection.getLastModified();
                if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED
                        || (lastModified != 0 && hasTimestamp && timestamp >= lastModified)) {
                    // not modified so no file download. just return
                    // instead and trace out something so the user
                    // doesn't think that the download happened when it
                    // didn't
                    return null;
                }
                // test for 401 result (HTTP only)
                if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    String message = "HTTP Authorization failure";
                    throw new IOException(message);
                }
            }

            //REVISIT: at this point even non HTTP connections may
            //support the if-modified-since behaviour -we just check
            //the date of the content and skip the write if it is not
            //newer. Some protocols (FTP) don't include dates, of
            //course.
            return connection;
        }
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:71,代碼來源:HttpDownloadHelper.java

示例6: isNotModified

public static boolean isNotModified(@Nullable Response response) {
    //noinspection SimplifiableIfStatement
    if (response == null) {
        return false;
    }
    return response.code() == HttpURLConnection.HTTP_NOT_MODIFIED;
}
 
開發者ID:TryGhost,項目名稱:Ghost-Android,代碼行數:7,代碼來源:NetworkUtils.java

示例7: download

/**
 * Check if there is a new version of the script engine
 * 
 * @throws IOException
 *             if any error occur
 */
private void download() throws IOException {
    boolean is32 = "32".equals( System.getProperty( "sun.arch.data.model" ) );
    String fileName;
    final String os = System.getProperty( "os.name", "" ).toLowerCase();
    if( os.contains( "windows" ) ) {
        fileName = is32 ? "win32" : "win64";
    } else if( os.contains( "mac" ) ) {
        fileName = is32 ? "mac" : "mac64";
    } else if( os.contains( "linux" ) ) {
        fileName = is32 ? "linux-i686" : "linux-x86_64";
    } else {
        throw new IllegalStateException( "Unknown OS: " + os );
    }
    File target = new File( System.getProperty( "java.io.tmpdir" ) + "/SpiderMonkey" );
    URL url = new URL( "https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central/jsshell-" + fileName
                    + ".zip" );
    System.out.println( "\tDownload: " + url );
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    if( target.exists() ) {
        System.out.println( "\tUP-TP-DATE" );
        conn.setIfModifiedSince( target.lastModified() );
    }
    InputStream input = conn.getInputStream();
    command = target.getAbsolutePath() + "/js";
    if( conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED ) {
        return;
    }
    ZipInputStream zip = new ZipInputStream( input );
    long lastModfied = conn.getLastModified();
    do {
        ZipEntry entry = zip.getNextEntry();
        if( entry == null ) {
            break;
        }
        if( entry.isDirectory() ) {
            continue;
        }
        File file = new File( target, entry.getName() );
        file.getParentFile().mkdirs();

        Files.copy( zip, file.toPath(), StandardCopyOption.REPLACE_EXISTING );
        file.setLastModified( entry.getTime() );
        if( "js".equals( file.getName() ) ) {
            file.setExecutable( true );
        }
    } while( true );
    target.setLastModified( lastModfied );
}
 
開發者ID:i-net-software,項目名稱:JWebAssembly,代碼行數:54,代碼來源:SpiderMonkey.java

示例8: fetchConferenceDataIfNewer

/**
 * Fetches data from the remote server.
 *
 * @param refTimestamp The timestamp of the data to use as a reference; if the remote data
 *                     is not newer than this timestamp, no data will be downloaded and
 *                     this method will return null.
 *
 * @return The data downloaded, or null if there is no data to download
 * @throws IOException if an error occurred during download.
 */
public String[] fetchConferenceDataIfNewer(String refTimestamp) throws IOException {
    if (TextUtils.isEmpty(mManifestUrl)) {
        LOGW(TAG, "Manifest URL is empty (remote sync disabled!).");
        return null;
    }

    BasicHttpClient httpClient = new BasicHttpClient();
    httpClient.setRequestLogger(mQuietLogger);

    // Only download if data is newer than refTimestamp
    // Cloud Storage is very picky with the If-Modified-Since format. If it's in a wrong
    // format, it refuses to serve the file, returning 400 HTTP error. So, if the
    // refTimestamp is in a wrong format, we simply ignore it. But pay attention to this
    // warning in the log, because it might mean unnecessary data is being downloaded.
    if (!TextUtils.isEmpty(refTimestamp)) {
        if (TimeUtils.isValidFormatForIfModifiedSinceHeader(refTimestamp)) {
            httpClient.addHeader("If-Modified-Since", refTimestamp);
        } else {
            LOGW(TAG, "Could not set If-Modified-Since HTTP header. Potentially downloading " +
                    "unnecessary data. Invalid format of refTimestamp argument: "+refTimestamp);
        }
    }

    HttpResponse response = httpClient.get(mManifestUrl, null);
    if (response == null) {
        LOGE(TAG, "Request for manifest returned null response.");
        throw new IOException("Request for data manifest returned null response.");
    }

    int status = response.getStatus();
    if (status == HttpURLConnection.HTTP_OK) {
        LOGD(TAG, "Server returned HTTP_OK, so new data is available.");
        mServerTimestamp = getLastModified(response);
        LOGD(TAG, "Server timestamp for new data is: " + mServerTimestamp);
        String body = response.getBodyAsString();
        if (TextUtils.isEmpty(body)) {
            LOGE(TAG, "Request for manifest returned empty data.");
            throw new IOException("Error fetching conference data manifest: no data.");
        }
        LOGD(TAG, "Manifest "+mManifestUrl+" read, contents: " + body);
        mBytesDownloaded += body.getBytes().length;
        return processManifest(body);
    } else if (status == HttpURLConnection.HTTP_NOT_MODIFIED) {
        // data on the server is not newer than our data
        LOGD(TAG, "HTTP_NOT_MODIFIED: data has not changed since " + refTimestamp);
        return null;
    } else {
        LOGE(TAG, "Error fetching conference data: HTTP status " + status);
        throw new IOException("Error fetching conference data: HTTP status " + status);
    }
}
 
開發者ID:dreaminglion,項目名稱:iosched-reader,代碼行數:61,代碼來源:RemoteConferenceDataFetcher.java

示例9: if

/**
 * Returns a <code>Collection</code> of <code>X509Certificate</code>s that
 * match the specified selector. If no <code>X509Certificate</code>s
 * match the selector, an empty <code>Collection</code> will be returned.
 *
 * @param selector a <code>CertSelector</code> used to select which
 *  <code>X509Certificate</code>s should be returned. Specify
 *  <code>null</code> to return all <code>X509Certificate</code>s.
 * @return a <code>Collection</code> of <code>X509Certificate</code>s that
 *         match the specified selector
 * @throws CertStoreException if an exception occurs
 */
@Override
@SuppressWarnings("unchecked")
public synchronized Collection<X509Certificate> engineGetCertificates
    (CertSelector selector) throws CertStoreException {

    if (ldap) {
        // caching mechanism, see the class description for more info.
        return (Collection<X509Certificate>)
            ldapCertStore.getCertificates(selector);
    }

    // Return the Certificates for this entry. It returns the cached value
    // if it is still current and fetches the Certificates otherwise.
    // For the caching details, see the top of this class.
    long time = System.currentTimeMillis();
    if (time - lastChecked < CHECK_INTERVAL) {
        if (debug != null) {
            debug.println("Returning certificates from cache");
        }
        return getMatchingCerts(certs, selector);
    }
    lastChecked = time;
    try {
        URLConnection connection = uri.toURL().openConnection();
        if (lastModified != 0) {
            connection.setIfModifiedSince(lastModified);
        }
        long oldLastModified = lastModified;
        try (InputStream in = connection.getInputStream()) {
            lastModified = connection.getLastModified();
            if (oldLastModified != 0) {
                if (oldLastModified == lastModified) {
                    if (debug != null) {
                        debug.println("Not modified, using cached copy");
                    }
                    return getMatchingCerts(certs, selector);
                } else if (connection instanceof HttpURLConnection) {
                    // some proxy servers omit last modified
                    HttpURLConnection hconn = (HttpURLConnection)connection;
                    if (hconn.getResponseCode()
                                == HttpURLConnection.HTTP_NOT_MODIFIED) {
                        if (debug != null) {
                            debug.println("Not modified, using cached copy");
                        }
                        return getMatchingCerts(certs, selector);
                    }
                }
            }
            if (debug != null) {
                debug.println("Downloading new certificates...");
            }
            // Safe cast since factory is an X.509 certificate factory
            certs = (Collection<X509Certificate>)
                factory.generateCertificates(in);
        }
        return getMatchingCerts(certs, selector);
    } catch (IOException | CertificateException e) {
        if (debug != null) {
            debug.println("Exception fetching certificates:");
            e.printStackTrace();
        }
    }
    // exception, forget previous values
    lastModified = 0;
    certs = Collections.emptySet();
    return certs;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:79,代碼來源:URICertStore.java

示例10: updateManifestCacheFile

private boolean updateManifestCacheFile(String name, String localCache, String url, ServletContext context)
	throws IOException
{
	File downloadtmp = File.createTempFile(name, ".part");
	File tmplocation = new File(_filesCacheDir);
	if(!tmplocation.exists())
	{	tmplocation.mkdir(); }
	File cacheFile = new File(tmplocation, localCache);
	long lastUpdatedCache = -1;
	if(cacheFile.exists())
	{
		lastUpdatedCache = cacheFile.lastModified();
		long twentyFourHoursAgo = System.currentTimeMillis() - (24L * 36000L);
		if(lastUpdatedCache > twentyFourHoursAgo)
		{
			context.log("Skipping updating " + name + " catalog");
			return false;
		}
	}
	URL cacheURL = new URL(url);
	HttpURLConnection cacheConnection = (HttpURLConnection) cacheURL.openConnection();
	if(lastUpdatedCache > 0L)
	{	cacheConnection.setIfModifiedSince(lastUpdatedCache); }
	cacheConnection.connect();
	switch(cacheConnection.getResponseCode())
	{
		case HttpURLConnection.HTTP_OK:
			InputStream is = cacheConnection.getInputStream();
			if("application/octet-stream".equals(cacheConnection.getContentType()))
			{
				ZipInputStream zis = new ZipInputStream(is);
				zis.getNextEntry();
				is = zis;
			}
			FileOutputStream os = new FileOutputStream(cacheFile, false);
			byte[] buff = new byte[1024];
			for(int br = is.read(buff); br > 0; br = is.read(buff))
			{	os.write(buff, 0, br); }
			os.close();
			is.close();
			context.log("manifest " + name + " updated");
			break;
		case HttpURLConnection.HTTP_NOT_MODIFIED:
			context.log("manifest " + name + " not modified");
			break;
		default:
			context.log("error updating " + name + ", got return code " + cacheConnection.getResponseCode() +" with message " + cacheConnection.getResponseMessage());
	}
	cacheConnection.disconnect();
	return true;
}
 
開發者ID:zueski,項目名稱:playswith,代碼行數:51,代碼來源:ManifestServlet.java


注:本文中的java.net.HttpURLConnection.HTTP_NOT_MODIFIED屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。