效果图如下所示:点击按钮,图片显示
代码如下:
package kongjian;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.protocol.HttpContext;
import com.example.kongjian.R;
import android.R.integer;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
/**
* 从网络上获取图片
*
* @author DongYan
*
*/
public class ImageViewInternet extends Activity {
private ImageView image;
private Button btn_image;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.imageviewinternet);
image = (ImageView) findViewById(R.id.image);
btn_image = (Button) findViewById(R.id.btn_image);
btn_image.setOnClickListener(new ClickListener());
}
class ClickListener implements OnClickListener {
/**
* 点击按钮从网络获取图片
*/
@Override
public void onClick(View v) {
byte [] imageget= ImageGet();
image.setImageBitmap(BitmapFactory.decodeByteArray(imageget, 0, imageget.length));
}
}
/**
* 从网络获取图片的方法
* @return
*/
public byte[] ImageGet() {
ByteArrayOutputStream byteArroutSream = new ByteArrayOutputStream();
try {
URL url = new URL(
"http://pic.baike.soso.com/p/20090715/20090715173716-552026492.jpg");//图片在网络上的地址
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3000);// 设置链接超时
// 获取服务器响应
connection.setDoInput(true);
// 请求方式
connection.setRequestMethod("GET");
// 得到响应码
int code = connection.getResponseCode();
if (code == 200) {// 响应成功
// 拿到图片信息
InputStream stream = connection.getInputStream();
// 将信息已字节的形式存储
byte[] data = new byte[6078];
int len;
while ((len = stream.read(data)) != -1) { // 如果没有读完
// 将写到数组中
byteArroutSream.write(data, 0, len);
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArroutSream.toByteArray();
}
}
还要注意的一点是要在AndroidManifest.xml 中添加权限
<uses-permission android:name="android.permission.INTERNET" />