安卓开发之HttpURLConnection类和Handler类的使用

package com.lidaochen.test;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTools {
    // 把InputStream转换成String
    public static String readStream(InputStream in) throws Exception
    {
        // 定义一个内存输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int len = -1;
        byte[] buffer = new byte[1024]; // 1kb
        while ((len = in.read(buffer)) != -1)
        {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        in.close();
        String content = new String(byteArrayOutputStream.toByteArray());
        return content;
    }
}
package com.lidaochen.test;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class MainActivity extends AppCompatActivity {
    protected final int REQUESTSUCESS = 0;
    protected final int REQUESTNOTFOUND = 1;
    protected final int REQUESTEXCEPTION = 2;
    private EditText et_path;
    private TextView tv_result;
    // 在主线程中定义一个handler
    private Handler handler = new Handler()
    {
        // 这个方法是在主线程里面执行的
        @Override
        public void handleMessage(android.os.Message msg) {
           // super.handleMessage(msg);
           // 区分一下是发送的哪条消息
            switch (msg.what)
            {
                case REQUESTSUCESS:
                    // 代表请求成功
                    String content = (String)msg.obj;
                    tv_result.setText(content);
                    break;
                case REQUESTNOTFOUND:
                    Toast.makeText(getApplicationContext(), "请求的资源不存在!", Toast.LENGTH_SHORT).show();
                    break;
                case REQUESTEXCEPTION:
                    Toast.makeText(getApplicationContext(), "服务器繁忙,请稍后......", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 找到EditText控件
        et_path = (EditText)findViewById(R.id.et_path);
        // 找到EditText控件
        tv_result = (TextView)findViewById(R.id.tv_result);
    }
    // 避免anr 可以把耗时的操作放到子线程中
    // 在4.0之后谷歌强制要求连接网络不能在主线程进行访问
    // 只有主线程才可以更新UI
    public void click(View v)
    {
        // 创建一个子线程
        new Thread()
        {
            public void run()
            {
                try
                {
                    // 获取源码网址路径
                    String path = et_path.getText().toString().trim();
                    // 创建URL对象,指定我们要访问的网址
                    URL url = new URL(path);
                    // 拿到HttpURLConnection对象,用于发送或者接收数据
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    // 设置发送get请求
                    connection.setRequestMethod("GET"); // get要求大小,其实默认就是get请求
                    // 设置请求超时时间
                    connection.setReadTimeout(5000);
                    // 获取服务器返回的状态码
                    int code = connection.getResponseCode();
                    // 如果code == 200说明请求成功
                    if (code == 200)
                    {
                        // 获取服务器返回的数据,是以流的形式返回的
                        InputStream is = connection.getInputStream();
                        // 使用我们定义的工具类,把is 转换成String
                        String content = StreamTools.readStream(is);
                        // 创建message对象
                        Message msg = new Message();
                        msg.what = REQUESTSUCESS;
                        msg.obj = content;
                        // 用我们创建的handler助手给系统发消息
                        handler.sendMessage(msg);
                    }
                    else
                    {
                        // 请求资源不存在  Toast是一个view 也不能在在线程更新ui
                        Message msg = new Message();
                        msg.what = REQUESTNOTFOUND;
                        handler.sendMessage(msg);
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = REQUESTEXCEPTION;
                    handler.sendMessage(msg);
                }
            }
        }.start();
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_path"
        android:hint="请输入网址..."/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查看"
        android:onClick="click"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/tv_result"/>
    </ScrollView>
</LinearLayout>

猜你喜欢

转载自www.cnblogs.com/duxie/p/10932827.html