• Android入门:查看服务器图片应用



    一、网络图片查看器需求

     

    存在一个Web服务器,其中存在一个图片,在Android客户端能够访问这张图片并在Android客户端显示;

     

    当点击“提交”后,则会显示指定服务器的图片;

    需要注意的一点是:我们不能使用localhost表示本机,而需要使用局域网的IP地址,否则会抛Connection confused异常;


    二、核心代码介绍

     

    在AndroidManifest.xml中加入:

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

    (1)URL url = new URL("http://.....");   //将字符串转为URL类型

    (2)HttpURLConnection conn = (HttpURLConnection)url.openConnection();

    (3)conn.setRequestMethod("GET");     //设置请求方法,如GET POST

    (4)conn.setReadTimeout(milliseconds);    //设置读超时时间

    (5)int code = conn.getResponseCode();      //获得响应码,如200表示OK,404表示无资源

    (6)InputStream in = conn.getInputStream();   //获得输入流

    (7)Bitmap bitmap = BitmapFactory.decodeByteArray(byte[]data,int begin,int length);   // 根据byte[] 转变为位图

    (8)imageView.setImageBitmap(Bitmap bitmap);


    三、全部代码


    搭建Web服务器的过程我就忽略了,此处我们使用最常用的Tomcat,版本为7.0.6;

    MainActivity.java

    package org.xiazdong.view.image;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    	private EditText editText;
    	private Button button;
    	private ImageView imageView;
    	private OnClickListener listener = new OnClickListener(){
    
    		@Override
    		public void onClick(View v) {
    			Bitmap bitmap = null;
    			try {
    				bitmap = getImage(editText.getText().toString());
    			} catch (Exception e) {
    				e.printStackTrace();
    				Toast.makeText(MainActivity.this, "获取图片失败",Toast.LENGTH_SHORT).show();
    			}
    			if(bitmap!=null)
    				imageView.setImageBitmap(bitmap);
    			else{
    				Toast.makeText(MainActivity.this, "获取图片失败",Toast.LENGTH_SHORT).show();
    			}
    		}
    
    		private Bitmap getImage(String path) throws Exception {
    			URL url = new URL(path);
    			HttpURLConnection con = (HttpURLConnection) url.openConnection();
    			byte[]data ;
    			con.setRequestMethod("GET");
    			if(con.getResponseCode()==200){
    				InputStream in = con.getInputStream();
    				data = read2Byte(in);
    				return BitmapFactory.decodeByteArray(data, 0, data.length);
    			}
    			else return null;
    		}
    	};
    	@Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            editText = (EditText)this.findViewById(R.id.imagepath);
            button = (Button)this.findViewById(R.id.button);
            imageView = (ImageView)this.findViewById(R.id.imageview);
            button.setOnClickListener(listener);
        }
    	private byte[] read2Byte(InputStream in) throws IOException {
    		byte[] data;
    		ByteArrayOutputStream bout = new ByteArrayOutputStream();
    		byte[]buf = new byte[1024];
    		int len = 0;
    		while((len = in.read(buf))!=-1){
    			bout.write(buf, 0, len);
    		}
    		data = bout.toByteArray();
    		return data;
    	}
    }

    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="图片路径"
             />
        <!-- 此处不能用localhost,一定要用ip地址 -->
        <EditText 
            android:id="@+id/imagepath"
             android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="http://192.168.0.103:8080/Server/logo.png" 
            />
        <Button 
            android:id="@+id/button"
             android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="提交"
            />
        <ImageView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageview"
            />
    
    </LinearLayout>




  • 相关阅读:
    java.net.DatagramPacket/java.net.DatagramSocket-UDP Socket编程
    新浪微博客户端(9)-实现版本新特性的ViewPager
    新浪微博客户端(8)-添加按钮到TabBar
    iOS-Auto property synthesis will not synthesize property 'delegate'; it will be implemented by its super
    新浪微博客户端(7)-通过转换坐标系来调整首页下拉菜单的位置
    新浪微博客户端(6)-创建首页下拉菜单
    TortoiseGit-创建分支、合并分支
    BZOJ2683: 简单题(cdq分治 树状数组)
    BZOJ3262: 陌上花开(cdq分治)
    BZOJ1901: Zju2112 Dynamic Rankings(整体二分 树状数组)
  • 原文地址:https://www.cnblogs.com/xiazdong/p/3058330.html
Copyright © 2020-2023  润新知