Android利用HttpUrlConnection制作网页源码查看器

在这里插入图片描述
运行效果如上图
下面开始实现该项目
第一步:主页面布局,这就不做过多叙述了,主要就是一个输入框,一个按钮,一个文本标签放在滚动视图里面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

    <EditText
            android:id="@+id/et_path"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入查看的网址"
            android:inputType=""/>

    <Button

            android:onClick="click"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="查看"
            />

    <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <TextView
                android:id="@+id/tv_result"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
    </ScrollView>


</LinearLayout>

在这里插入图片描述
第二步:新建类StreamTools 该类将输入流转化成一个字符串

package com.example.a15114.weblook;

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

public class StreamTools {
    //把流inputstream 转换成一个string
    public static String readStream(InputStream in) throws IOException {
        //定义一个内存输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = -1;

        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) != -1) {
            baos.write(buffer, 0, len);

        }
        in.close();
        String content = new String(baos.toByteArray());


        return content;
    }
}

第三步:在Activity内编写代码

package com.example.a15114.weblook;

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

import javax.net.ssl.HttpsURLConnection;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private static final int REQUESTSUCESS = 0;
    private static final int REQUESTNOTFOUND = 1;

    EditText et_path;
    TextView tv_result;
    /*Handler handler = new Handler() {
        //这个方法实在主线程里面进行的 所以可以在这儿更新ui
        @Override
        public void handleMessage(Message 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;
            }

        }
    };*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_path = findViewById(R.id.et_path);
        tv_result = findViewById(R.id.tv_result);

        //[1.1]打印当前线程名字
        System.out.println();

    }

    public void click(View view) {

        //[2.0]创建一个子线程
        new Thread() {
            @Override
            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 = (HttpsURLConnection) 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]获取服务器返回的数据 是以流的形式返回的 由于把流转换成字符串是一个非常常见的操作 所以把他作为一个工具类(utils)

                        InputStream in = conn.getInputStream();

                        //[2.9]使用我们定义的工具类,把in转换成string
                        final String content = StreamTools.readStream(in);

                       /* //[2.9.0]创建message
                        Message msg = new Message();
                        msg.what = REQUESTSUCESS;
                        msg.obj = content;

                        //[2.9.1]拿着我们创建的handler告诉系统 我们要更新ui
                        handler.sendMessage(msg);//发了一条消息 把数据放到了msg里面 handmessage就会执行
*/
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_result.setText(content);
                            }
                        });
                    } else {
                        //请求资源不存在 toast是一个view 也不能在子线程更新ui
                       /* Message msg = new Message();
                        msg.what = REQUESTNOTFOUND;//代表哪条消息
                        handler.sendMessage(msg);*/
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "获取失败", Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }

        }.start();


    }
}

使用httpurlconnection就只有几步 定义路径 通过路径拿到http对象 设置请求方法 超时时间 然后就是判断返回码了 因为返回的数据是通过流的形式所以这里想要显示成文本 就只有将流转化成字符串类型
在这里插入图片描述

**注意:**因为这是耗时操作,所以只能在子线程中进行,而更新UI又需要在主线程中进行所以可以通过Message 和Handler做到 或者在子线程中使用runOnuithread方法也可以。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Android Studio 中,可以使用 HttpUrlConnection 类来发送网络请求。下面是一个简单的示例代码,演示如何使用 HttpUrlConnection 发送 GET 请求: ```java public class HttpUrlConnectionExample { public static void main(String[] args) { try { URL url = new URL("http://example.com/api/data"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream inputStream = conn.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder result = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { result.append(line); } bufferedReader.close(); inputStream.close(); String responseData = result.toString(); // 解析响应数据 System.out.println(responseData); } conn.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } ``` 其中,URL 表示请求地址,HttpURLConnection 类可以使用 openConnection() 方法打开连接,设置请求方法为 GET,并调用 connect() 方法建立连接。如果响应状态码为 HTTP_OK,则读取响应数据并进行解析。 发送 POST 请求时,需要设置请求方法为 POST,并设置请求数据。示例如下: ```java public class HttpUrlConnectionExample { public static void main(String[] args) { try { URL url = new URL("http://example.com/api/data"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); OutputStream outputStream = conn.getOutputStream(); String requestData = "key1=value1&key2=value2"; outputStream.write(requestData.getBytes()); outputStream.close(); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream inputStream = conn.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder result = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { result.append(line); } bufferedReader.close(); inputStream.close(); String responseData = result.toString(); // 解析响应数据 System.out.println(responseData); } conn.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } ``` 其中,setDoOutput(true) 表示请求数据可以写入请求体,setDoInput(true) 表示响应数据可以读取。将请求数据写入 OutputStream,并调用 connect() 方法建立连接。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值