简体   繁体   English

Android:如何知道位于 web 服务器中的文件已修改?

[英]Android: how to know file located in web server is modified?

I am parsing Xml file located in web server and storing parsed data in to database.我正在解析位于 web 服务器中的 Xml 文件并将解析的数据存储到数据库中。 for my app I am using data from database.对于我的应用程序,我正在使用数据库中的数据。 I need to parse the xml file only if the file is modified otherwise no need to parse.只有当文件被修改时,我才需要解析 xml 文件,否则不需要解析。 So how can I know the file is modified?那么我怎么知道文件被修改了呢? I know I can use "if-modified-since" header.我知道我可以使用“if-modified-since”header。 But I need some examples of "if-modified-since" header但我需要一些“if-modified-since”的例子 header
please help me.......请帮我.......

Since you are retrieving your.xml file from a web server, this should be relatively easy without having to do a server side MD5 sum.由于您正在从 web 服务器检索您的 .xml 文件,因此这应该相对容易,无需进行服务器端 MD5 总和。

If you are doing a HTTP request for the xml file you can simply perform a HEAD request from the web server and this will return if the file has changed/modified or if it doesn't exist.如果您正在对 xml 文件执行 HTTP 请求,您可以简单地从 web 服务器执行 HEAD 请求,如果文件已更改/修改,它将不会返回。 This is also lightweight and the best part is that the server should already do this for you.这也是轻量级的,最好的部分是服务器应该已经为您执行此操作。

Edit : re-reading your question, looks like you had the same idea.编辑:重新阅读你的问题,看起来你有同样的想法。 Here's the code.这是代码。

import java.net.*;
import java.io.*;

// Using HTTP_NOT_MODIFIED
public static boolean Changed(String url){
    try {
      HttpURLConnection.setFollowRedirects(false);
      HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
      con.setRequestMethod("HEAD");
      return (con.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED);
    }
    catch (Exception e) {
       e.printStackTrace();
       return false;
    }
  }

// GET THE LAST MODIFIED TIME
public static long LastModified(String url)
{
  HttpURLConnection.setFollowRedirects(false);
  HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
  long date = con.getLastModified();

  if (date == 0)
    System.out.println("No last-modified information.");
  else
    System.out.println("Last-Modified: " + new Date(date));

  return date;
}

See:看:

Alternatively if your server supports them you can use ETags to find out if your file has been modified.或者,如果您的服务器支持它们,您可以使用 ETags 来确定您的文件是否已被修改。

Calculate the MD5 of the file.计算文件的MD5。 You can save the old one and compare it?你可以保存旧的并比较它吗?

If you don't know how, check out this for example: Getting a File's MD5 Checksum in Java如果您不知道如何操作,请查看以下示例: Getting a File's MD5 Checksum in Java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM