访问网络数据

本文详细介绍了在Android应用中访问网络数据的方法,包括使用标准ImageView和SmartImageView加载图片,以及访问并解析HTML数据的过程。文章提供了从网络获取资源的代码示例,展示了如何处理网络请求、解析响应,并在UI线程上更新界面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

访问网络数据

添加权限: <uses-permission android:name="android.permission.INTERNET"/>

1. 访问图片

xml文件布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<EditText
    android:id="@+id/pathEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="https://www.baidu.com/img/bd_logo1.png"/>
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="加载"
    android:onClick="click"/>
<ImageView 
    android:id="@+id/photoImageView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</LinearLayout>

android:text="https://www.baidu.com/img/bd_logo1.png"写死的,可以通过代码写入

代码实现

   public class MainActivity extends Activity {
    protected static final int UPDATE_UI = 0;
    private EditText pathEditText;
    private ImageView photoImageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pathEditText = (EditText) this.findViewById(R.id.pathEditText);
        photoImageView = (ImageView) this.findViewById(R.id.photoImageView);
    }

    /**
     * 去访问网络,获取对应的图片,加载到手机中 
     */
    public void click(View view){
        //旧规:1.0,2.0,3.0主线程或叫做UI主线程,可以去做非常耗时的操作
        //新规1:4.0,5.0,6.0子线程去访问网络这样非常耗时的操作,即子线程去做耗时的操作,今天
        new Thread(){
            public void run() {
                try {
                    //获取网络图片路径
                    String path = pathEditText.getText().toString().trim();
                    //创建URL对象
                    URL url = new URL(path);
                    //获取与服务器的连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //设置请求的方式
                    conn.setRequestMethod("GET");
                    //设置连接超时时间,在5秒之内有结果响应,否则出错
                    conn.setConnectTimeout(5000);

                    //获取服务器的响应流
                    InputStream is = conn.getInputStream();
                    //将输入流转成一个图片(Bitmap)
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    //新规2:子线程禁止修改手机界面,如果子线程要修改手机界面,必须发送消息给UI主线程,让UI主线程修改界面
                    //创建消息对象
                    Message message = new Message();
                    //设置子线程要让主线程做什么事
                    message.what = UPDATE_UI;
                    //子线程得让图片给主线程
                    message.obj = bitmap;
                    //子线程发送消息对象到UI主线程
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                    //访问网络失败
                }
            }
        }.start();
    }
//消息处理器
    private Handler handler = new Handler(){
        //主线程分别处理不同子线程的需求,只要有子线程发送消息,主线程的这个方法就会被回调,参数就是子线程发送过来的消息
        public void handleMessage(Message message) {
            //获取消息的类别
            switch(message.what){
                case UPDATE_UI:
                     //获取子线程发送过来的图片
                     Bitmap bitmap = (Bitmap) message.obj;
                     //主线程来更新手机界面
                     photoImageView.setImageBitmap(bitmap);
                     //退出
                     break;
            }
        }
    };
}

2.通过SmartImageView加载图片

项目中导入SmartImageView框架

xml文件布局中将

<ImageView 
    android:id="@+id/photoImageView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

替换为

<com.loopj.android.image.SmartImageView
    android:id="@+id/iv_piv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

代码实现

public class MainActivity extends Activity {
    private EditText et_path;
    private SmartImageView iv_piv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_path = (EditText) findViewById(R.id.et_path);
        iv_piv = (SmartImageView) findViewById(R.id.iv_piv);
    }
    public void click(View view){
        String path=et_path.getText().toString().trim();
        iv_piv.setImageUrl(path);
    }
}

3. 访问html数据

xml文件布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
    android:id="@+id/pathTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="https://www.baidu.com/"
    android:textSize="22sp" />
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="加载/"
    android:onClick="load"/>
<ScrollView
     android:layout_width="match_parent"
     android:layout_height="match_parent">
    <TextView
        android:id="@+id/htmlTextView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</ScrollView>
</LinearLayout>

代码实现

public class MainActivity extends Activity {
    protected static final int UPDATE_UI = 0;
    protected static final int NET_ERROR = 1;
    protected static final int SERVER_ERROR = 2;

    private TextView pathTextView;
    private TextView htmlTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pathTextView = (TextView) this.findViewById(R.id.pathTextView);
        htmlTextView = (TextView) this.findViewById(R.id.htmlTextView);
    }
    private Handler handler = new Handler(){
        public void handleMessage(Message message) {
            switch(message.what){
                case UPDATE_UI:
                     String html = (String) message.obj;
                     if(html!=null){
                         htmlTextView.setText(html+"");
                     }else{
                         Toast.makeText(MainActivity.this,"加载失败",0).show(); 
                     }
                     break;
                case NET_ERROR:
                     Toast.makeText(MainActivity.this,"访问网络失败",0).show();   
                     break;
                case SERVER_ERROR:
                     Toast.makeText(MainActivity.this,"服务器响应失败",0).show();  
                     break;
            }
        }
    };
    public void load(View view){
        new Thread(){
            public void run() {
                HttpURLConnection conn = null;
                try {
                    String path = pathTextView.getText().toString().trim();
                    URL url = new URL(path);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    //获取服务器的响应状态码
                    int code = conn.getResponseCode();  
                    //如果响应状态码为200
                    if(code == 200){
                        InputStream is = conn.getInputStream();
                        String html = StringFactory.decodeStream(is);
                        Message message = new Message();
                        message.what = UPDATE_UI;
                        message.obj = html;
                        handler.sendMessage(message);
                    }else{
                        Message message = new Message();
                        message.what = SERVER_ERROR;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //访问网络失败
                    Message message = new Message();
                    message.what = NET_ERROR;
                    handler.sendMessage(message);
                }
                conn.disconnect();
            }
        }.start();
    }
}

public class StringFactory {
    /**
     * 将InputStream转成String
     */
    public static String decodeStream(InputStream is){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[2048];
            int len = 0;
            while((len=is.read(buf))>0){
                baos.write(buf,0,len);
            }
            baos.flush();
            byte[] data = baos.toByteArray();
            return new String(data,"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

转载于:https://www.cnblogs.com/konekou/p/7699115.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值