gpt4 book ai didi

java - Android:下载 .html 并将其转换为 String

转载 作者:太空狗 更新时间:2023-10-29 16:05:38 25 4
gpt4 key购买 nike

我需要从某个 URL 下载 .html 文件。我该怎么做?以及如何将其转换为字符串?

更新:

我不知道你为什么投反对票。仅使用一种方法 stringWithContentsOfURL:encoding:error:,我就可以在 iOS 上获得所需的结果。我建议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);
}
}
}

关于java - Android:下载 .html 并将其转换为 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15940114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com