1>从网络上获取数据(图片,网页,xml,json等)
?
A.从网络上获取一张图片,然后显示到手机上
这是在java中
public class ImageRequest {
?/**
? * @param args
? */
?public static void main(String[] args) throws Exception {
??URL url = new URL("http://i3.itc.cn/20100707/76c_0969b700_d5b4_41cd_8243_9b486be92cc4_0.jpg");
??HttpURLConnection conn = (HttpURLConnection)url.openConnection();
??conn.setRequestMethod("GET");
??conn.setConnectTimeout(5 * 1000);
??InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
??byte[] data = readInputStream(inStream);//得到图片的二进制数据
??File imageFile = new File("itcast.jpg");//保存在项目下
??FileOutputStream outStream = new FileOutputStream(imageFile);
??outStream.write(data);
??outStream.close();
?}
?public static byte[] readInputStream(InputStream inStream) throws Exception{
??ByteArrayOutputStream outStream = new ByteArrayOutputStream();
??byte[] buffer = new byte[1024];//定义一个1k的缓冲区
??int len = 0;
??while( (len=inStream.read(buffer)) != -1 ){//返回的是实际的字节数
???outStream.write(buffer, 0, len);//将缓冲区的数据写入到内存中
??}
??inStream.close();
??return outStream.toByteArray();
?}
}
在手机上
?button.setOnClickListener(new View.OnClickListener() {
???@Override
???public void onClick(View v) {
????String path = pathText.getText().toString();
????try {
?????byte[] data = ImageService.getImage(path);
?????Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);//生成位图
?????imageView.setImageBitmap(bitmap);//显示图片?????
????} catch (Exception e) {
?????Toast.makeText(ImageShowActivity.this, R.string.error, 1).show();
?????Log.e(TAG, e.toString());
????}
???}});
<!-- 访问网络的权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
public class StreamTool {
?/**
? * 从输入流中获取数据
? * @param inStream 输入流
? * @return
? * @throws Exception
? */
?public static byte[] readInputStream(InputStream inStream) throws Exception{
??ByteArrayOutputStream outStream = new ByteArrayOutputStream();
??byte[] buffer = new byte[1024];
??int len = 0;
??while( (len=inStream.read(buffer)) != -1 ){
???outStream.write(buffer, 0, len);
??}
??inStream.close();
??return outStream.toByteArray();
?}
}
-----------------------------------------------------------------
public class ImageService {
?
?public static byte[] getImage(String path) throws Exception {
??URL url = new URL("http://i3.itc.cn/20100707/76c_0969b700_d5b4_41cd_8243_9b486be92cc4_0.jpg");
??HttpURLConnection conn = (HttpURLConnection)url.openConnection();
??conn.setRequestMethod("GET");
??conn.setConnectTimeout(5 * 1000);
??InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
??return StreamTool.readInputStream(inStream);//得到图片的二进制数据
?}
}
B.从网络上获取网页(用的比较少)
byte[] data = readInputStream(inStream);//得到网页的二进制数据
String html = new String(data,"gb2312");
C.从网络上获取xml数据,然后显示在手机上
?android手机模拟器本身绑定在模拟器上,所以访问web service的时候不能用local host
?或者用127.0.0.1。而应该使用局域网上的ip地址。
public class VideoService {
?/**
? * 获取最新的视频资讯
? * @return
? * @throws Exception
? */
?public static List<Video> getLastVideos() throws Exception{