Android学习笔记——Http通信
此篇学习笔记主要内容:
- 使用WebView控件加载网页
- 使用ImageView控件加载网络图片
效果图如下:
具体步骤
使用WebView控件加载网页
1.创建一个名为Http的简单Android程序。
2.在布局文件中添加Composite>WebView组件。
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
3.在MainActivity.java中为WebView初始化:
private WebView webView;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView=(WebView)findViewById(R.id.webView1);
4.创建新类HttpThread,继承自java.lang.Thread,初始化并重写run()方法,具体代码如下:
public class HttpThread extends Thread {
private String url;
private WebView webView;
private Handler handler;
//加载网页
HttpThread(String url,WebView webView,Handler handler){
this.url = url;
this.webView = webView;
this.handler = handler;
}
@Override
public void run(){
try {
URL httpUrl = new URL(url);
try {
HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
conn.setReadTimeout(5000);//请求可延时时间范围
conn.setRequestMethod("GET");//请求方式
/*********加载网页***********/
final StringBuffer sb = new StringBuffer();
//读入流,读入网页内数据
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
while((str=reader.readLine())!=null){
//每次读一行
sb.append(str);
}
handler.post(new Runnable(){
@Override
public void run(){
//webView加载本地信息,第二个参数为所加载网页的html中<meta>标签的content属性值
webView.loadData(sb.toString(), "text/html; charset=utf-8", null);
}
});
/*********加载网页结束***********/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
5.在MainActivity中的onCreate中执行:
new HttpThread("http://www.yimispace.cn/", webView, handler).start();//第一个参数为想要加载的网页
6.在AndroidManifest中声明网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
7.运行,此时可显示在控件WebView中所加载的网页。
继续,使用ImageView控件加载网络图片
8.在布局文件中加Images&Madia>ImageView控件。
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
9.与HttpThread类相似的,新建HttpImgThread类,继承自java.lang.Thread,代码如下:
public class HttpImgThread extends Thread {
private String url;
private ImageView imageView;
private Handler handler;
//加载图片
HttpImgThread(String url,ImageView imageView,Handler handler){
this.url = url;
this.imageView = imageView;
this.handler = handler;
}
@Override
public void run(){
try {
URL httpUrl = new URL(url);
try {
HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
conn.setReadTimeout(5000);//请求可延时时间范围
conn.setRequestMethod("GET");//请求方式
/*********加载网页图片***********/
conn.setDoInput(true);
InputStream in = conn.getInputStream();//获取图片流
FileOutputStream out = null;
File downloadFile = null;
String fileName = String.valueOf(System.currentTimeMillis());
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//判断SD卡是否挂载
File parent = Environment.getExternalStorageDirectory();
downloadFile = new File(parent, fileName);
out = new FileOutputStream(downloadFile);//下载图片文件
}
byte[] b = new byte[2*1024];
int len;
if(out!=null){
while((len=in.read(b))!=-1){
out.write(b, 0, len);//循环读取到本地
}
}
//解析图片
final Bitmap bitmap = BitmapFactory.decodeFile(downloadFile.getAbsolutePath());
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
imageView.setImageBitmap(bitmap);
}
});
/*********加载网页图片结束***********/
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
10.在MainActivity中初始化ImageView控件:
private ImageView imageView;
并在onCreate方法中添加
imageView=(ImageView)findViewById(R.id.imageView1);
和
new HttpImgThread("http://www.yimispace.cn/images/img1.jpg", imageView, handler).start();//第一个参数为网络图片的地址
11.在AndroidManifest中添加权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>