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

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();

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

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

我还没有在网上搜索这个内容,所以我会非常感谢您的一点见解!

感谢。

有帮助吗?

解决方案

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

其他提示

这是为您完成的一段代码。除了你想要做的事情之外,它还能够处理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.RetrievePage Phramer项目

尝试使用此代码,它可能无法编译,因为我没有测试它,但它应该可以解决所有可能的异常未被捕获,但您可以轻松添加它。请注意超时,永远不要使用无限超时,因为如果资源不可用,您的程序将来某个时候会挂起。如果您所做的不仅仅是简单的文本文件检索,您可以查看 HTTPClient Apache Commons。

    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());
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top