前面说到的网络通信是用以socket的方式,是标准的java接口,但是操作还是比较繁琐,这里介绍用HttpURLConnection通信的方法,这里添加两个实例:
1.加载网络页面
package com.linxiaosheng.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpConnection;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;
import com.linxiaosheng.R;
public class MyHttp extends Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.myhttp);
String url="http://www.baidu.com";
Handler handler=new Handler();
webView=(WebView)findViewById(R.id.webView1);
//启动线程
new HttpThread(url, webView, handler).start();
}
}
//由于网络通信是比较耗时的操作,需要把把单独放在一个线程里面
class HttpThread extends Thread{
private String path;
private WebView webView;
private Handler handler;
public HttpThread(String path,WebView webView,Handler handler){
this.path=path;
this.webView=webView;
this.handler=handler;
}
@Override
public void run() {
// TODO Auto-generated method stub
URL httpUrl;
try {
httpUrl = new URL(path);
try {
HttpURLConnection connection=(HttpURLConnection) httpUrl.openConnection();
//这里请求方法需要大写
connection.setRequestMethod("GET");
//设置网络连接超时时间
connection.setConnectTimeout(5000);
final StringBuffer sb=new StringBuffer();
BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str="";
while((str=br.readLine())!=null){
sb.append(str);
}
System.out.println(sb.toString());
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//加载图片资源
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();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
这里因为要访问网络通信,需要添加权限
<uses-permission android:name="android.permission.INTERNET"/>
2.加载网络图片
package com.linxiaosheng.http;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;
import com.linxiaosheng.R;
public class MyHttp2 extends Activity {
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myhttp2);
String path="http://d.hiphotos.baidu.com/image/pic/item/902397dda144ad347a82f507d3a20cf431ad8574.jpg";
Handler handler=new Handler();
ImageView imageView=(ImageView)findViewById(R.id.imageView1);
new HttpThread2(path,imageView,handler).start();
};
}
class HttpThread2 extends Thread{
private ImageView imageView;
private Handler handler;
private String path;
public HttpThread2(String path,ImageView imageView,Handler handler){
this.imageView=imageView;
this.handler=handler;
this.path=path;
}
public void run(){
URL url;
try {
url = new URL(path);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setReadTimeout(5000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
File file=null;
FileOutputStream os=null;
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File basepath=Environment.getExternalStorageDirectory();
Log.i("sysout", basepath.getAbsolutePath());
String filename=Long.toString(System.currentTimeMillis());
file=new File(basepath,filename);
/*if(!file.exists()){
file.createNewFile();
}*/
Log.i("sysout", file.getAbsolutePath());
os=new FileOutputStream(file);
}
//Log.i("sysout", file.getAbsolutePath());
if(os!=null){
byte[] b=new byte[1024*4];
int len=0;
while((len=connection.getInputStream().read(b))!=-1){
os.write(b,0,len);
}
final Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
imageView.setImageBitmap(bitmap);
}
});
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/abc_ab_bottom_solid_dark_holo" />
</LinearLayout>
这里要读写SD卡,需要加入以下权限
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>