简单的网页源码查看器

简单的网页源码查看器,主要用到的知识点HttpURLConnection还有输入输出流以及handler

首先布局大概是这个样子的actiity_main.xml文件中

<?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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.httpurlconnection.MainActivity"
    tools:showIn="@layout/activity_main">
    <EditText
        android:id="@+id/et_url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入网址"
        />
    <Button
        android:onClick="click"
        android:id="@+id/bt_look"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="23sp"
        android:text="查看"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tv_result"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textSize="20sp"
            />
    </ScrollView>

</LinearLayout>

然后自定义了一个转换工具类StreamTools(把流转换成字符串的工具)

package com.example.httpurlconnection;

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

/**
 * //把流转换成字符串的工具
 * Created by Administrator on 2016-06-24.
 */
public class StreamTools {
    //把一个inputStream转换成String
    public  static String readStream(InputStream in)throws Exception{
        //定义一个内存输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = -1;
        byte[] buffer = new byte[1024];//1kb
        while ((len = in.read(buffer))!= -1){
            baos.write(buffer,0,len);
        }
        in.close();
        String content = new String(baos.toByteArray());
        return  content;
    }
}

最后在MainActivity文件中代码如下

package com.example.httpurlconnection;

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 java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private EditText et_path;
    private TextView tv_result;
    //在主线程中定义一个handler
   /* private Handler handler = new Handler() {
        //这个方法在主线程里面执行
        @Override
        public void handleMessage(Message msg) {
            String content = (String) msg.obj;
            //2.10 把数据显示到textview上
            tv_result.setText(content);
        }
    };*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1找到我们关心的控件
        et_path = (EditText) findViewById(R.id.et_url);
        tv_result = (TextView) findViewById(R.id.tv_result);
    }

    //2、点击按钮进行查看 指定路径的源码
    public void click(View v) {
        //2.0创建一个子线程
        new Thread() {
            public void run() {
                try {
                    //2.1获取源码路径
                    String path = et_path.getText().toString().trim();
                    //2.2创建URL 对象指定我们要访问的网址
                    URL url = new URL(path);

                    //2.3拿到httpurlconnection对象  用于发送或者接受数据
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //2.4设置发送get请求
                    conn.setRequestMethod("GET");//get要求大写  默认就是get请求
                    //2.5设置请求超时时间
                    conn.setConnectTimeout(5000);
                    //2.6获取服务器返回的状态码
                    int code = conn.getResponseCode();
                    //2.7如果code==200 说明请求成功
                    if (code == 200) {
                        //2.8 获取服务器返回的数据  服务器是以流的形式返回的
                        InputStream in = conn.getInputStream();
                        //2.9 使用我们定义的工具类把in转成成String
                        final String content = StreamTools.readStream(in);

                        //2.9.0创建message对象
                       // Message msg = new Message();
                        //2.9.1拿到我们定义的handler 告诉系统 我要更新UI
                       // handler.sendMessage(msg);//发了一条消息 消息(msg)里把数据放到了msg里 handleMessage就执行
                       // msg.obj = content;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_result.setText(content);
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            };}.start();
    }

}
主要用的是GET请求方式。



 

你可能感兴趣的:(android,handler,Inputstream,android联网请求)