1

如标题所示,我正在尝试通过 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();

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

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

我还没有在网上搜索过这个,所以一点见解将不胜感激!

谢谢。

4

3 回答 3

3

这是一段代码,可以为您做到这一点。除了您尝试执行的操作之外,它还能够处理 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项目

于 2009-09-15T14:29:11.593 回答
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());
于 2009-09-15T14:29:27.133 回答
2

查看Apache Commons 的HttpClient,特别是getResponseBodyAsString()方法。

于 2009-09-15T14:28:04.640 回答