从网络上获取图片

来源:互联网 发布:浅喜似苍狗 知乎 编辑:程序博客网 时间:2024/05/16 07:22

效果图如下所示:点击按钮,图片显示


代码如下:

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;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.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 {/** * 点击按钮从网络获取图片 */@Overridepublic 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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return  byteArroutSream.toByteArray();}}



还要注意的一点是要在AndroidManifest.xml 中添加权限

<uses-permission android:name="android.permission.INTERNET" />





0 0