【问题标题】:HTTP/1.1 302 Moved Temporarily - Happens on Android API 16-17HTTP/1.1 302 暂时移动 - 发生在 Android API 16-17
【发布时间】:2017-02-27 13:08:17
【问题描述】:

长话短说。当我的应用程序启动时,我想从互联网上下载一些谷歌表格文件。情况如下:

较新的设备:一切正常 100%,没有问题,所有文件都已下载。

旧设备 (API 16-17): 正确下载第一个工作表文件。 无法下载第二个文件。我遇到 HTTP/1.1 302 已临时移动问题,文件无法正确下载。

我为这两个文件调用了 AsynchTask。 AsynchTask 运行完美,我尝试了其他方法来查看 AsynchTask 是否是问题所在。此外,所有链接都完美无缺。

这是我的 AsynchTask 类代码的一部分:

下载文件的方法:

private String downloadUrl(String urlString) throws IOException {
    InputStream is = null;

    try {
        URL url = new URL(urlString);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setInstanceFollowRedirects(true);  //you still need to handle redirect manully.
        HttpsURLConnection.setFollowRedirects(true);
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int responseCode = conn.getResponseCode();
        is = conn.getInputStream();

        String contentAsString = convertStreamToString(is);
        Log.d("contentAsString",contentAsString);
        return contentAsString;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

字符串结果(HTTP/1.1 302 Moved Temporarily 消息)

 HTTP/1.1 302 Moved Temporarily
      Content-Type: text/html; charset=UTF-8
      Cache-Control: no-cache, no-store, max-age=0, must-revalidate
      Pragma: no-cache
      Expires: Mon, 01 Jan 1990 00:00:00 GMT
      Date: Tue, 18 Oct 2016 09:26:14 GMT
      Location: https://docs.google.com/spreadsheets/d/1hRiDvdLPkQEdTSVxmWEoWXjmCFQodNjMNYi3Fd7yYn0/gviz/tq
      P3P: CP="This is not a P3P policy! See https://support.google.com/accounts/answer/151657?hl=en for more info."
      P3P: CP="This is not a P3P policy! See https://support.google.com/accounts/answer/151657?hl=en for more info."
      Content-Encoding: gzip
      X-Content-Type-Options: nosniff
      X-XSS-Protection: 1; mode=block
      Server: GSE
      Set-Cookie: NID=89=afVN4Sa74ZsYuffxNSiXn2wWTJkSUULbtZperbpr8T9hPzHoFzx-uGu_lJUVCkYSd1eZUPUFucffCDHc7lPConnfPpTMbqAOgIcIQoJG6TQFUHzBUNW6bFqUy__ZthsR;Domain=.google.com;Path=/;Expires=Wed, 19-Apr-2017 09:26:14 GMT;HttpOnly
      Set-Cookie: NID=89=k5r33ZLA4l__4v1CE1iGrtQbtqoJxOyVxwrSMbsKWviK74u-vM32WdKtt-txFEOhPWo1g9f1CWMXcu6Fuczo4ZCck47D23tIZZRcqpRxkSB0z5w2xI9oj1Jcq8duISiU;Domain=.google.com;Path=/;Expires=Wed, 19-Apr-2017 09:26:14 GMT;HttpOnly
      Alt-Svc: quic=":443"; ma=2592000; v="36,35,34,33,32"
      Transfer-Encoding: chunked

      00000001
      
      00000001
      �
      00000001
      
      00000001
      ��
      00000001
      ��
      00000001
      ��
      00000001
      ��
      00000001
      ��
      00000001
      ��
      00000001
      ��
      00000001
      m
      00dc
      ��N�0D��
      �ܳ�8 !7R�8)ih�hs��U�R�!6��q
      G����HoY!�2�X����,J�TfFI��L�4��~����Z�~��eݬ�]D����E��.�k�n$i��/���r,%E��U΍��gl�ӟ1>
      v���V!:���Y�/�;.��ۗ�s�?��&��=U�v���õ�,���op4Q8!�4�=�
      %��O����ڛ�����
      0

在阅读了一些关于 HTTP 302 的信息后,我知道我必须以某种方式重定向。问题是我不知道该怎么做。另外,我不知道为什么这个问题只出现在较旧的 android 版本上。

我已经挣扎了一个星期了。任何反馈表示赞赏!谢谢!

【问题讨论】:

    标签: java android http https httpsurlconnection


    【解决方案1】:

    遵循重定向的关键是通过键 location 获取标题并将其用作您的 URL:

    Location: https://docs.google.com/spreadsheets/d/1hRiDvdLPkQEdTSVxmWEoWXjmCFQodNjMNYi3Fd7yYn0/gviz/tq
    

    这只是网络服务器说“嘿,你的页面移到这里。改为去那里!”的方式。

    这个article by mkyong.com 有一个很好的例子:

    package com.mkyong.http;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class HttpRedirectExample {
        public static void main(String[] args) {
            try {
                String url = "http://www.twitter.com";
    
                URL obj = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
                conn.setReadTimeout(5000);
                conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
                conn.addRequestProperty("User-Agent", "Mozilla");
                conn.addRequestProperty("Referer", "google.com");
    
                System.out.println("Request URL ... " + url);
    
                boolean redirect = false;
    
                // normally, 3xx is redirect
                int status = conn.getResponseCode();
                if (status != HttpURLConnection.HTTP_OK) {
                    if (status == HttpURLConnection.HTTP_MOVED_TEMP
                    || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                        redirect = true;
                }
    
                System.out.println("Response Code ... " + status);
    
                if (redirect) {
                    // get redirect url from "location" header field
                    String newUrl = conn.getHeaderField("Location");
    
                    // get the cookie if need, for login
                    String cookies = conn.getHeaderField("Set-Cookie");
    
                    // open the new connnection again
                    conn = (HttpURLConnection) new URL(newUrl).openConnection();
                    conn.setRequestProperty("Cookie", cookies);
                    conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
                    conn.addRequestProperty("User-Agent", "Mozilla");
                    conn.addRequestProperty("Referer", "google.com");
    
                    System.out.println("Redirect to URL : " + newUrl);
                }
    
                BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuffer html = new StringBuffer();
    
                while ((inputLine = in.readLine()) != null) {
                    html.append(inputLine);
                }
                in.close();
    
                System.out.println("URL Content... \n" + html.toString());
                System.out.println("Done");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

    • 我去看看!谢谢。将返回反馈!
    • :thumbsup: 好消息 :)
    猜你喜欢
    • 2019-01-18
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    相关资源
    最近更新 更多