Pergunta

Estou tentando baixar um arquivo sobre HTTP e armazenar seu conteúdo em uma string, como diz o título. Minha abordagem é assim:

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

O código falha quando tenta ler a partir do fluxo, relatando que o fluxo está fechado.

Agora, se você tentar acessar o arquivo através de um navegador, ele não será servido como texto, mas como um arquivo a ser baixado.

Eu não cheguei a nenhum lugar pesquisando na web nisso, então um pequeno insight seria muito apreciado!

Obrigado.

Foi útil?

Solução

Verificação de saída HttpClient de Apache Commons, em particular o getResponseBodyasstring () método.

Outras dicas

Aqui está um pedaço de código que faz isso por você. Além do que você está tentando fazer, também é capaz de lidar Accept-Encoding: gzip, deflate) e detecta automaticamente a codificação para você (necessária para manusear strings).

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

O código é de info.olteanu.utils.retrieve.RetrievePage, Projeto Phramer.

Experimente este código, ele pode não compilar, pois não o testei, mas deve funcionar além de todas as exceções possíveis não serem capturadas, mas você pode adicionar isso facilmente. Observe os tempos limite, nunca use tempos limites infinitos, pois seu programa ficará em algum momento no futuro se o Ressource não estiver disponível. Se você está fazendo mais do que um simples recuperação de arquivos de texto, você pode dar uma olhada HttpClient do 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());
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top