从Dropbox中的txt文件下载文本

时间:2013-01-31 15:37:17

标签: java android

我有一个.txt文件上传到Dropbox中的Public文件夹。如果单击该文件,它将打开,您可以看到该文本,如果您检查HTML源代码,它只显示文件内的文本(没有HTML标记,只是字符串)。有没有办法将该文本下载到String变量?

1 个答案:

答案 0 :(得分:1)

  • 首先通过HttpUrlConnection打开文件。
  • 然后在缓冲区中读取文件。
  • 只需buffer.toString();

这是代码:

URL url = new URL("Link to dropbox");
                HttpURLConnection.setFollowRedirects(true);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setDoOutput(false);
                con.setReadTimeout(20000);
                con.setRequestProperty("Connection", "keep-alive");

                con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0");
                ((HttpURLConnection) con).setRequestMethod("GET");
                //System.out.println(con.getContentLength()) ;
                con.setConnectTimeout(5000);
                BufferedInputStream in = new BufferedInputStream(con.getInputStream());
                int responseCode = con.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    System.out.println(responseCode);
                }
                StringBuffer buffer = new StringBuffer();
                int chars_read;
                //int total = 0;
                while ((chars_read = in.read()) != -1) 
                {
                    char g = (char) chars_read;
                    buffer.append(g);
                }
                final String page = buffer.toString();

将所有这些放在一个新线程和一个try-catch块中。

相关问题