ある URL から .html ファイルをダウンロードする必要があります。どうすればいいですか?そして、どうすれば文字列に変換できますか?
更新しました:
あなたが反対票を投じる理由がわかりません。1 つのメソッドを使用するだけで、iOS で目的の結果を得ることができますstringWithContentsOfURL:encoding:error:
。そして、Androidにも同様の機能があることを提案しました。方法
以下のコードは、リンクから html ページをダウンロードし、完了コールバックで文字列に変換された html ページを返します
public class HTMLPageDownloader extends AsyncTask<Void, Void, String> {
public static interface HTMLPageDownloaderListener {
public abstract void completionCallBack(String html);
}
public HTMLPageDownloaderListener listener;
public String link;
public HTMLPageDownloader (String aLink, HTMLPageDownloaderListener aListener) {
listener = aListener;
link = aLink;
}
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(link);
String html = "";
try {
HttpResponse response = client.execute(request);
InputStream in;
in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
html = str.toString();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return html;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (!isCancelled()) {
listener.completionCallBack(result);
}
}
}
http://jsoup.orgライブラリまたは
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}finally {
urlConnection.disconnect();
}
入力ストリームを文字列に変換します
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
br.close();