如何从服务器

时间:2016-04-07 08:58:04

标签: android apk httpconnection

我试图从我的服务器上的apk文件中获取最后修改日期,问题一旦我尝试获取标题就会以某种方式失败。

我可以用

下载文件
try {
            HttpURLConnection.setFollowRedirects(false);
            HttpURLConnection con =  (HttpURLConnection) new URL(params[0]).openConnection();

            con.setRequestMethod("HEAD");
            return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
        } // do some more not relevant

但是一旦我尝试从服务器获取标题,它就会失败

            URL obj = new URL(customURL);
            URLConnection conn = obj.openConnection();
            Map<String, List<String>> map = conn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                System.out.println("Key : " + entry.getKey()
                        + " ,Value : " + entry.getValue());
                Toast.makeText(getApplicationContext(),"Key: "+entry.getKey() + "Value: " + entry.getValue(),Toast.LENGTH_SHORT).show();
            }

我已经尝试了这个,但也使用已经存在的连接,只是使用con ..但它都以某种方式失败

任何帮助都会非常好

2 个答案:

答案 0 :(得分:0)

尝试这可能有所帮助,

long date = con.getLastModified();

 HttpURLConnection.setFollowRedirects(false);
 HttpURLConnection con = (HttpURLConnection) new URL(fileUrl).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

供参考, http://developer.android.com/reference/java/net/URLConnection.html#getLastModified%28%29

答案 1 :(得分:-1)

我发现我犯的错误是在异步任务中运行它然后尝试在Toast中查看结果。

一旦我把它放入runOnUiThread

就会运行
final long date = urlConnection.getLastModified();

        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(),"GGG"+ date,Toast.LENGTH_SHORT).show();
            }
        });