【问题标题】:How to download a file over HTTP and store its content in a String in Java如何通过 HTTP 下载文件并将其内容存储在 Java 中的字符串中
【发布时间】:2010-11-28 11:44:59
【问题描述】:

如标题所示,我正在尝试通过 HTTP 下载文件并将其内容存储在字符串中。因此,我的方法是:

URL u = new URL("http://url/file.txt");

ByteArrayBuffer baf = new ByteArrayBuffer(32);
InputStream in = (InputStream) u.getContent(); 
BufferedInputStream bis = new BufferedInputStream(in);

int buffer;
while((buffer = bis.read()) != -1){
    baf.append((byte)buffer);
}

bis.close();
in.close();

代码尝试从流中读取时失败,报告流已关闭。

现在,如果您尝试通过浏览器访问该文件,它将不会以文本形式提供,而是以要下载的文件形式提供。

我还没有在网上搜索到任何地方,因此非常感谢您提供一点见解!

谢谢。

【问题讨论】:

    标签: java download file-get-contents


    【解决方案1】:

    查看来自 Apache Commons 的 HttpClient,尤其是 getResponseBodyAsString() 方法。

    【讨论】:

    【解决方案2】:

    这里有一段代码可以为您做到这一点。除了您尝试执行的操作之外,它还能够处理 GZip 压缩(如果您在标头中使用 Accept-Encoding: gzip, deflate 设置它)并自动为您检测编码(处理字符串所必需的)。

    private InputStream prepareInputStream(String urlToRetrieve) throws IOException
    {
        URL url = new URL(urlToRetrieve);
        URLConnection uc = url.openConnection();
        if (timeOut > 0)
        {
            uc.setConnectTimeout(timeOut);
            uc.setReadTimeout(timeOut);
        }
        InputStream is = uc.getInputStream();
        // deflate, if necesarily
        if ("gzip".equals(uc.getContentEncoding()))
            is = new GZIPInputStream(is);
    
        this.lastURLConnection = uc;
        return is;
    }
    // detects encoding associated to the current URL connection, taking into account the default encoding
    public String detectEncoding()
    {
        if (forceDefaultEncoding)
            return defaultEncoding;
        String detectedEncoding = detectEncodingFromContentTypeHTTPHeader(lastURLConnection.getContentType());
        if (detectedEncoding == null)
            return defaultEncoding;
    
        return detectedEncoding;
    }
    
    
    public static String detectEncodingFromContentTypeHTTPHeader(String contentType)
    {
        if (contentType != null)
        {
            int chsIndex = contentType.indexOf("charset=");
            if (chsIndex != -1)
            {
                String enc = StringTools.substringAfter(contentType , "charset=");
                if(enc.indexOf(';') != -1)
                    enc = StringTools.substringBefore(enc , ";");
                return enc.trim();
            }
        }
        return null;
    }
    
    
    // retrieves into an String object
    public String retrieve(String urlToRetrieve)
    throws MalformedURLException , IOException
    {
        InputStream is = prepareInputStream(urlToRetrieve);
        String encoding = detectEncoding();
        BufferedReader in = new BufferedReader(new InputStreamReader(is , encoding));
        StringBuilder output = new StringBuilder(BUFFER_LEN_STRING);
        String str;
        boolean first = true;
        while ((str = in.readLine()) != null)
        {
            if (!first)
                output.append("\n");
            first = false;
            output.append(str);
        }
        in.close();
        return output.toString();
    }
    

    代码来自info.olteanu.utils.retrieve.RetrievePagePhramer project

    【讨论】:

      【解决方案3】:

      试试这段代码,它可能无法编译,因为我没有测试过它,但它应该可以工作,除了所有可能的异常都没有被捕获,但你可以很容易地添加它。请注意超时,切勿使用无限超时,因为如果资源不可用,您的程序将在未来某个时候挂起。如果您要做的不仅仅是简单的文本文件检索,您可以查看 Apache Commons 的 HTTPClient

          URL url = new URL("http://mydomain.com/file.txt");
          URLConnection urlConnection = url.openConnection();
          urlConnection.setConnectTimeout(1000);
          urlConnection.setReadTimeout(1000);
          BufferedReader breader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
      
          StringBuilder stringBuilder = new StringBuilder();
      
          String line;
          while((line = breader.readLine()) != null) {
              stringBuilder.append(line);
          }
      
          System.out.println(stringBuilder.toString());
      

      【讨论】:

      • 哦,没有处理字符集。但是这段代码应该给你一个起点。
      • 我已经试过了,它读取的是一个空字符串。让我检查一下 HTTPClient。
      猜你喜欢
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多