HTTP経由でファイルをダウンロードし、そのコンテンツをJavaの文字列に保存する方法
-
07-07-2019 - |
質問
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();
ストリームからの読み取りを試みるとコードが失敗し、ストリームが閉じられたことが報告されます。
ブラウザからファイルにアクセスしようとしても、ダウンロードされるファイルとしてではなく、テキストとしては提供されません。
これでウェブを検索しているところがないので、少し洞察をいただければ幸いです!
ありがとう。
解決
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());
所属していません StackOverflow