通过身份验证从URL下载.xls文件

时间:2018-08-29 22:12:02

标签: android file authentication download xls

我正在尝试通过身份验证从网站下载Excel文件。通常,如果我手动将链接复制到Web浏览器,则会出现一个弹出窗口,显示File.xls保存或取消。不确定如何能够通过Android以编程方式下载此文件。

我似乎无法正常工作。我可以从链接下载Excel文件,但是当我打开该文件时,它不受支持。我意识到我只是在创建文件,需要登录才能下载文件。

所以第一个问题是我尝试使用以下代码进行身份验证,甚至不确定我是否已登录或是否有效;

public void CheckAuthenticate(){

    try {
        // Sets the authenticator that will be used by the networking code
        // when a proxy or an HTTP server asks for authentication.
        Authenticator.setDefault(new CustomAuthenticator());
        URL url = new URL("http://*****.com/account/login");
        // read text returned by server
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String line;
        while ((line = in.readLine()) != null) {
            //System.out.println(line);
        }
        in.close();
    }
    catch (MalformedURLException e) {
        System.out.println("Malformed URL: " + e.getMessage());
    }
    catch (IOException e) {
        System.out.println("I/O Error: " + e.getMessage());
    }
}

public static class CustomAuthenticator extends Authenticator {
    // Called when password authorization is needed
    protected PasswordAuthentication getPasswordAuthentication() {
        // Get information about the request
        String prompt = getRequestingPrompt();
        String hostname = getRequestingHost();
        InetAddress ipaddr = getRequestingSite();
        int port = getRequestingPort();
        String email = "XXXXXXX";
        String password = "XXXXXXX";

        System.out.println("prompt: " + prompt);
        System.out.println("hostname: " + hostname);
        System.out.println("requesting site: " + ipaddr);

        // Return the information (a data holder that is used by Authenticator)
        return new PasswordAuthentication(email, password.toCharArray());

    }
}

第二个问题是我不确定我是否在正确地执行以下代码:

 URL url = new URL(downloadUrl);//Create Download URl
            HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
            c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
            c.connect();//connect the URL Connection

0 个答案:

没有答案