Android下载网站HTML内容 [英] Android Downloading website HTML content
本文介绍了Android下载网站HTML内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我正在尝试在Logcat中下载网站HTML内容,以便将来我可以选择将来的特定信息.但是在我可以这样做之前,我想先测试一下是否可以联系该网站.目前,我没有收到错误,但也没有得到上下文.
Hello I'm attempting to download a websites HTML content within my Logcat so that in the future I can pick out specific information in the future. But before I can do that I want to test if I can contact the website first. Currently I'm not getting an error but I'm not getting the context either.
//我创建的公共类
public class DownloadTsk extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
//Oncreate方法
// Oncreate method
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTsk task = new DownloadTsk();
String result = null;
try {
result = task.execute("http://www.posh24.com/celebrities").get();
Log.i("Content", result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//当前结果
Content: <!DOCTYPE html>
<html>
<head>
推荐答案
如果您想知道连接是否成功,则应该使用
If you want to know if you connected successfully then you should use
int responseCode = urlConnection.getResponseCode();
实际上这是我从HTTP请求中获取结果的方式:
And actually this is how I am getting the result from the HTTP request:
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
这篇关于Android下载网站HTML内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文