«

Android网络开发-URL

时间:2024-3-2 17:38     作者:韩俊     分类: Android


URL

通俗点说,在3W上每一种资源都有一个统一的地址,这个地址就叫URL(Uniform Resource Locator)

JAVA URL

使用java中java.net.URL类和java.net.URLConnection类可以比较方便的进行网络通信。

import java.io.*;
import java.net.*;
public class URLTest
{
    public static void main(String args[])
    {
        try
        {
            URL u1=new URL("http://mil.news.sohu.com/");
            System.out.println(u1.getProtocol());
            System.out.println(u1.getHost());
            System.out.println(u1.getPort());
            System.out.println(u1.getFile());
        }
        catch(MalformedURLException e)
        {
            System.out.println(e);
        }
        catch(IOException ee)
        {
            System.out.println(ee);
        }
        catch(Exception eee)
        {
            System.out.println(eee);
        }    
    }
}

安卓网络图片加载

main.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <ImageView
        android:id="@+id/myImageView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center" />
</LinearLayout>

LoadPicture

加载网络图片有其他高级的用法,和一些库,本文主要是讲URL,用最普通的方式,参考一些开源代码

public class LoadPictrue {

    private String uri;
    private ImageView imageView;
    private byte[] picByte;

    public void getPicture(String uri,ImageView imageView){
        this.uri = uri;
        this.imageView = imageView;
        new Thread(runnable).start();
    }

    @SuppressLint("HandlerLeak")
    Handler handle = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (picByte != null) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(picByte, 0, picByte.length);
                    imageView.setImageBitmap(bitmap);
                }
            }
        }
    };

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(uri);
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.setRequestMethod("GET");
                conn.setReadTimeout(10000);

                if (conn.getResponseCode() == 200) {
                    InputStream fis =  conn.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] bytes = new byte[1024];
                    int length = -1;
                    while ((length = fis.read(bytes)) != -1) {
                        bos.write(bytes, 0, length);
                    }
                    picByte = bos.toByteArray();
                    bos.close();
                    fis.close();

                    Message message = new Message();
                    message.what = 1;
                    handle.sendMessage(message);
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
}

MainActivity

    public static final String picUrl = "https://www.baidu.com/img/bdlogo.png";
    String url;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = (Button)findViewById(R.id.myButton);
        final TextView tv = (TextView)findViewById(R.id.myEditText);
        final ImageView iv = (ImageView)findViewById(R.id.myImageView);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tv.getText())){
                    url = picUrl;
                }
                else{
                    url = tv.getText().toString();
                }
                new NormalLoadPictrue().getPicture(url,iv);
            }
        });
    }

要点

要熟悉字节流和字符的转换,stream和reader的区别
注意网络异常的处理顺序
使用消息机制,不要堵塞主线程

标签: android

热门推荐