class DownLoadTextListener implements OnClickListener{
@Override
public void onClick(View v) {
String stringUrl = "URL资源地址";
new DownloadTextTask().execute(stringUrl);
}
}
//为防止网络延迟影响主线程,so用其它线程访问URL下载资源
private class DownloadTextTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls) {
HttpDownLoader httpDownLoader = new HttpDownLoader();
String txt = httpDownLoader.download(urls[0]);
System.out.println(txt);
return txt;
}
}
public String download(String urlStr){
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try {
//创建一个URL对象
url = new URL(urlStr);
//创建一个Http链接
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
//字节流转字符流转缓冲流
buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while((line=buffer.readLine())!=null){
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
buffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
@Override
public void onClick(View v) {
String stringUrl = "URL资源地址";
new DownloadTextTask().execute(stringUrl);
}
}
//为防止网络延迟影响主线程,so用其它线程访问URL下载资源
private class DownloadTextTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls) {
HttpDownLoader httpDownLoader = new HttpDownLoader();
String txt = httpDownLoader.download(urls[0]);
System.out.println(txt);
return txt;
}
}
public String download(String urlStr){
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try {
//创建一个URL对象
url = new URL(urlStr);
//创建一个Http链接
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
//字节流转字符流转缓冲流
buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while((line=buffer.readLine())!=null){
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
buffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}