先看一下代码:
package com.example.testjsonpic;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
public class MainActivity extends Activity
{
public static final String DATA="http://www.baidu.com/img/baidu_sylogo1.gif";
public static final String DATA_="http://x.limgs.cn/f2/c1/up201301/342a0432638526a1c79471d86f3d7192.jpg";
ImageView image = null,image02 = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initsView();
}
public void initsView()
{
//通过第一种方法获取
this.image = (ImageView) findViewById(R.id.image);
image.setImageBitmap(getHttpBitmap(DATA));
//通过第二种方法获取
this.image02 = (ImageView) findViewById(R.id.image02);
image02.setImageBitmap(getBitmap(DATA_));
}
//第一种方法
public Bitmap getHttpBitmap(String data)
{
Bitmap bitmap = null;
try
{
//初始化一个URL对象
URL url = new URL(data);
//获得HTTPConnection网络连接对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5*1000);
connection.setDoInput(true);
connection.connect();
//得到输入流
InputStream is = connection.getInputStream();
Log.i("TAG", "*********inputstream**"+is);
bitmap = BitmapFactory.decodeStream(is);
Log.i("TAG", "*********bitmap****"+bitmap);
//关闭输入流
is.close();
//关闭连接
connection.disconnect();
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
//第二种方法
public Bitmap getBitmap(String s)
{
Bitmap bitmap = null;
try
{
URL url = new URL(s);
bitmap = BitmapFactory.decodeStream(url.openStream());
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
}
需要运行,还要在AndroidManifest.xml中加入网络权限。
<uses-permission android:name="android.permission.INTERNET"/>
发现在4.0以上版本的模拟器中,用HttpUrlConnection.getInputStream(),也就是第一种方法,不能运行解析出图片,会报错,而通过URL.openStream()方法则没有问题。原因在于,4.0以后的版本要求必须开一个线程来执行网络数据请求,不能直接写入主线程了,所以改代码如下:
package com.itehema.NetText;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnClickListener{
private EditText pathText;
private ImageView Image;
private NetService service;
private Button goButton;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String path="http://www.baidu.com/img/baidu_sylogo1.gif";
pathText = (EditText) this.findViewById(R.id.pathEdit);
pathText.setText(path);
Image = (ImageView) this.findViewById(R.id.imageView1);
service = new NetService();
goButton = (Button) this.findViewById(R.id.pathGo);
goButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(){
public void run() {
try {
String path = pathText.getText().toString().trim();
final Bitmap image = service.getImage(path);
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Image.setImageBitmap(image);
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}.start();
}
}
package com.itehema.NetText;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class NetService {
public Bitmap getImage(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
File file = new File("/mnt/sdcard/" + URLEncoder.encode(path, "UTF-8"));
if (file.exists()) // 判断是否有缓存文件
conn.setIfModifiedSince(file.lastModified()); // 如果文件存在, 发送最后修改时间
int code = conn.getResponseCode();
System.out.println(code);
if (code == 200) {
InputStream in = conn.getInputStream(); // 获取输入流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int length;
while ((length = in.read(buffer)) != -1) // 读取数据
out.write(buffer, 0, length); // 写到内存
in.close();
out.close();
byte[] data = out.toByteArray();
Bitmap image = BitmapFactory.decodeByteArray(data, 0, data.length); // 把数据解码为图片
FileOutputStream fos = new FileOutputStream(file);
fos.write(data); // 把图片缓存到本地
fos.close();
return image;
}
else if (code == 304) {
return BitmapFactory.decodeFile(file.getAbsolutePath()); // 读取本地文件
}
throw new RuntimeException("网络异常: " + code);
}
}