`
wangfu_02
  • 浏览: 70842 次
社区版块
存档分类
最新评论

android开发积累4-android使用HttpURLConnection访问网络

阅读更多

android访问网络,可以使用java.net.HttpURLConnection类,下面的例子是在点一个button的时候,启动一个新的线程,下载一个网络图片数据,在ImageView上进行显示:

NetActivity.java

package Test.wangfu;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class NetActivity extends Activity {

    private ImageView view=null;
    private android.graphics.Bitmap bmp=null;
    private TextView text=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.net);
       
        Button btn=(Button)this.findViewById(R.id.downloadButton);
        view=(ImageView)this.findViewById(R.id.imageView2);
        text=(TextView)this.findViewById(R.id.label);
        btn.setOnClickListener(new OnClickListener(){

            public void onClick(View arg0) {
                HandlerThread thread=new HandlerThread("netthread");
                thread.start();
                Handler r=new Handler(thread.getLooper());
                text.setText("启动下载图片线程");
                r.postDelayed(new java.lang.Runnable(){

                    public void run() {
                        try {
                            java.net.URL url=new URL("http://www.taihe.com.cn/images/logo.gif");
                            try {
                                java.net.HttpURLConnection conn=(HttpURLConnection)url.openConnection();
                                NetActivity.this.runOnUiThread(new Runnable(){

                                    public void run() {
                                        // TODO Auto-generated method stub
                                        text.setText("开始请求网络图片资源");
                                    }});
                                conn.setDoInput(true);
                                conn.setUseCaches(false);
                                conn.setRequestMethod("GET");
                                conn.setConnectTimeout(5000);
                                java.io.InputStream is=conn.getInputStream();
                                final int length = (int) conn.getContentLength();
                                NetActivity.this.runOnUiThread(new Runnable(){

                                    public void run() {
                                        // TODO Auto-generated method stub
                                        text.setText("数据总长度为:"+String.valueOf(length));
                                    }});
                                if (length != -1) {
                                    byte[] imgData = new byte[length];
                                    byte[] buffer = new byte[512];
                                    int readLen = 0;
                                    int destPos = 0;
                                    while ((readLen = is.read(buffer)) > 0) {
                                        System.arraycopy(buffer, 0, imgData, destPos, readLen);
                                        destPos += readLen;
                                    }
                                    bmp = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
                                    NetActivity.this.runOnUiThread(new Runnable(){

                                        public void run() {
                                            // TODO Auto-generated method stub
                                            view.setImageBitmap(bmp);
                                        }});
                                   
                                }
                                conn.disconnect();
                               
                            } catch (final IOException ex) {
                                ex.printStackTrace();
                            }
                        } catch (final MalformedURLException e) {
                              e.printStackTrace();
                        }
                       
                    }}, 1000);
               
            }});
    }

}

 

net.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Enter Number to Dial:" />
     <ImageView
        android:id="@+id/imageView2"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.89" />
    
     <Button
        android:id="@+id/downloadButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DownLoad" />

</LinearLayout>

 

由于使用网络,需要在AndroidManifest.xml中添加权限。

<permission android:protectionLevel="normal" android:name="android.permission.INTERNET"></permission>

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

 

说明:

1、如果当网络访问直接在protected void onCreate(Bundle savedInstanceState)方法中执行的话,会出现android.os.NetworkOnMainThreadException错误,这是一个Android开发规范反馈的错误。

可以通过在onCreate中添加代码:

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectDiskReads()
        .detectDiskWrites()
        .detectNetwork()   // or .detectAll() for all detectable problems
        .penaltyLog()
        .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
        .detectLeakedSqlLiteObjects()
        .detectLeakedClosableObjects()
        .penaltyLog()
        .penaltyDeath()
        .build());

来解决。一般来讲,网络访问需要一定的请求时间,不建议网络访问在主线程中执行。

 

 

2、URL参数问题

java.net.URL url=new URL("http://www.taihe.com.cn/images/logo.gif");

如果java.net.URL不能正常解析参数的URL地址,可能会在 java.io.InputStream is=conn.getInputStream();这

语句的地方出错。测试时,可以先通过模拟器的浏览器先输入地址,看是否正常可以显示。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics