【问题标题】:Android download text file off WWWAndroid 从 WWW 下载文本文件
【发布时间】:2012-12-25 13:54:02
【问题描述】:

我正在使用适用于 Android 的 MonoDevelop,希望获得一些帮助以从 Internet 下载文本文件并将其存储在字符串中。

这是我的代码:

        try 
        {
            URL url = new URL("mysite.com/thefile.txt");

            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) 
            {
                // str is one line of text; readLine() strips the newline character(s)
            }

            in.close();
        } 
        catch (MalformedURLException e) 
        {

        } catch (IOException e) 
        {

        }

我收到以下错误:

无效的表达式术语'in';

能否请我帮忙以使此代码正常工作。如果有更简单的方法可以从 WWW 上下载文本文件并将内容保存到字符串中,请帮助我实现它。

提前致谢。

【问题讨论】:

    标签: c# text download monodevelop inputstream


    【解决方案1】:

    这是我们用于项目下载网站的代码。

    只需将此函数传递给您的 URI,您将返回一个包含整个网站的 BufferedReader。

       public static BufferedReader openConnection(URI uri) throws URISyntaxException, ClientProtocolException, IOException {
            HttpGet http = new HttpGet(uri);
            HttpClient client = new DefaultHttpClient();
            HttpResponse resp = (HttpResponse) client.execute(http);
            HttpEntity entity = resp.getEntity();
            InputStreamReader isr = new InputStreamReader(entity.getContent());
            BufferedReader br = new BufferedReader(isr, DNLD_BUFF_SIZE);
            return br;
        }
    

    您可以通过以下方式制作 uri:

    try{
        try{
        URI uri = new URI("mysite.com/thefile.txt");
        catch (Exception e){} //Should never occur
    
        BufferedReader in = openConnection(uri);
        String str;
            while ((str = in.readLine()) != null) 
            {
             // str is one line of text; readLine() strips the newline character(s)
            }
        in.close();
        } 
     catch (Exception e){
     e.printStackTrace();
     }
    

    这应该可以帮助您下​​载网站。

    【讨论】:

    • 如何从下载的缓冲区返回一个字符串。谢谢。
    • 'URI' 需要什么 using 语句?
    • 调用函数openConnection并传递uri时自动返回字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多