Android学习笔记---23_网络通信之网络图片查看器

Android学习笔记---23_网络通信之网络图片查看器
23_网络通信之网络图片查看器
----------------------------------------------
1.从Internet获取数据
------------------------------
利用HttpURLConnection对象,我们可以从网络中获取网页数据.
URL url = new URL(" http://www.sohu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);//设置连接超时
conn.setRequestMethod(“GET”);//以get方式发起请求
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();//得到网络返回的输入流
String result = readData(is, "GBK");
conn.disconnect();
//第一个参数为输入流,第二个参数为字符集编码
public static String readData(InputStream inSream, String charsetName) throws 

Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inSream.close();
return new String(data, charsetName);
}
利用HttpURLConnection对象,我们可以从网络中获取文件数据.
URL url = new URL(" http://photocdn.sohu.com/20100125/Img269812337.jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();
readAsFile(is, "Img269812337.jpg"); 

public static void readAsFile(InputStream inSream, File file) throws Exception{
FileOutputStream outStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
  outStream.close();
inSream.close();
}

----------------------------------------------------------------
2.下面是一个应用:
  通过用户输入的一个网络图片的地址,来获取网络图片
----------------------------------------------------------
3.创建项目:netimage
/netimage/src/com/credream/netimage/NetimageActivity.java
 package com.credream.netimage;


import com.credream.service.ImageService;


import android.app.Activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ImageView;

import android.widget.Toast;
import android.widget.SimpleAdapter.ViewBinder;


public class NetimageActivity extends Activity {
   
 /** Called when the activity is first created. */
  
 private EditText pathText;
  
 private ImageView imageView;
 
  @Override
   
 public void onCreate(Bundle savedInstanceState) {
   
     super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  
 pathText=(EditText)this.findViewById(R.id.imagepath);
  
 imageView=(ImageView)this.findViewById(R.id.imageview);
   Button button=

(Button)this.findViewById(R.id.button);
   button.setOnClickListener(new 

ButtonOnClickListener());
   

    }
  
  private final class ButtonOnClickListener implements View.OnClickListener{


@Override
public void onClick(View v)
{
String path=pathText.getText().toString();

//以字节数组存放图片的数据
byte[] data;
try
{
data = ImageService.getImage(path);
Bitmap bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);
//使用数组的全部数据来创建位图对象
imageView.setImageBitmap(bitmap);

catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), R.string.error, 1).show();

//当用户访问网络的时候,需要访问网络权限,因为可能把用户手机的东西传到网上
}
}
    
  
  } 
}
-------------------------------------------------------------------------
3./netimage/src/com/credream/service/ImageService.java
package com.credream.service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.credream.util.StreamTool;

public class ImageService
{
/**
 * 获取网络图片的数据
 * @param path 网络图片的路径
 * @return
 */
public static byte[] getImage(String path)throws Exception
{
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();//基于

Http协议链接对象
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
//InputStream inputStream=conn.getInputStream();//得到的返回数据,可能是错

误的比如,404
//错误的时候,也返回数据,但是返回的事错误数据不是所需要的
if(conn.getResponseCode()==200){
InputStream inStream=conn.getInputStream();
return StreamTool.read(inStream);//返回从流中读取的2进制数据
}
return null;
}

}
----------------------------------------------------------
4./netimage/src/com/credream/util/StreamTool.java
package com.credream.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
/**
 * 读取流中的数据
 * @author xiaofeng
 *
 */
public class StreamTool
{
public static byte[] read(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();
}

}
---------------------------------------------
4./netimage/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=" http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/imagepath" />
  <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/imagepath" 
        android:text=" http://192.168.1.110:6118/web/logo.gif"/>
  <!-- http://localhost:6118/web/logo.gif注意这个网站的地址是不能访问的,因为这个时

候,他会从android的系统中找这个
  部署的项目,但是找不到所以,要使用局域网的ip来访问,这个地址
   http://192.168.1.110:6118/web/logo.gif也就是本机的ip地址.-->
  <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button"
        android:id="@+id/button" />
    <ImageView 
           android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         android:id="@+id/imageview" 
         />
    
</LinearLayout>
----------------------------------------------------
5./netimage/res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, NetimageActivity!</string>
    <string name="app_name">网络通信之网络图片查看器</string>
     <string name="imagepath">网络图片路径</string>
       <string name="button">查看图片</string>
         <string name="error">获取图片失败</string>

</resources>
-----------------------------------------
6./netimage/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=" http://schemas.android.com/apk/res/android"
    package="com.credream.netimage"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".NetimageActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
<!-- 访问internet权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
        
</manifest>
------------------------------------------------------------
7.新建一个web项目:web
 a./web/WebContent/logo.gif
   直接访问就好了
------------------------------------
8.开始测试:
  a.首先把netimage项目部署在android的平台上
  c.运行web项目,右键run on server
----------------------------------------------------------------
1.注意获取网络上的任何数据都是一样的:
  a.首先获取数据流
  b.得到二进制数据,得到二进制数据后,然后就可以生成你需要格式的文件
---------------------------------------------------------------

你可能感兴趣的:(Android学习笔记---23_网络通信之网络图片查看器)