android | 网络权限 | http请求相关

无法使用https的情况下允许http请求,在Manifest.xml中加上:

android:usesCleartextTraffic="true"

要记得申请权限:

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

参考:https://blog.csdn.net/weixin_30877755/article/details/99263427

自己封装的http请求类:

package com.vnctf2022.cm1.utils;

// 这个类是Mz1封装的http请求类

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class MzHttp {
    private String url;       // 请求的url
    public String text;       // 请求的结果
    public byte[] content;     // 请求的结果
    public HashMap<String, String> params;          // 请求参数(post)

    // 构造方法
    public MzHttp(String url){
        this.url = url;
        params = new HashMap<String, String>();       // 初始化param表
    }
    // 获取字节数组类型
    public byte[] getContent() {
        return content;
    }
    // 获取文本类型
    public String getText() {
        this.text = new String(this.content);        // 转化为utf8字符串
        return text;
    }

    // 用于读取Stream数据
    private byte[] read(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];      // 一次读取1024bytes
        int len = 0;
        while((len = inStream.read(buffer)) != -1)
        {
            outStream.write(buffer,0,len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    // 发送get请求
    public void get(){
        try {
            //System.out.println("get ok");
            URL url = new URL(this.url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置连接超时为5秒
            conn.setConnectTimeout(5000);
            // 设置请求类型为Get类型
            conn.setRequestMethod("GET");
            // 判断请求Url是否成功
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("请求url失败");
            }
            InputStream inStream = conn.getInputStream();
            this.content = this.read(inStream);              // 将变量保存到content下来
            inStream.close();
        }catch (Exception e){
            // 异常处理
            e.printStackTrace();
        }
    }

    // 发送post请求
    // 默认情况下是x-www-form-urlencoded
    public void post(HashMap<String, String> params) {
        //System.out.println("post ok");
        try{
            HttpURLConnection conn = (HttpURLConnection) new URL(this.url).openConnection();
            //设置请求方式,请求超时信息
            conn.setRequestMethod("POST");      // 创建post请求
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            //设置运行输入,输出:
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //Post方式不能缓存,需手动设置为false
            conn.setUseCaches(false);
            //我们请求的数据:
            //String data = "passwd="+ URLEncoder.encode(passwd, "UTF-8")+
            //        "&number="+ URLEncoder.encode(number, "UTF-8");
            String data = "";
            for (String key: params.keySet()) {
                data += key+"="+URLEncoder.encode(params.get(key), "UTF-8")+"&";      // 循环创建请求数据
            }
            System.out.println(data);
            //这里可以写一些请求头的东东...
            //获取输出流
            OutputStream out = conn.getOutputStream();
            out.write(data.getBytes());
            out.flush();
            if (conn.getResponseCode() == 200) {
                InputStream inStream = conn.getInputStream();
                this.content = this.read(inStream);              // 将变量保存到content下来
                inStream.close();
            }else{
                // 处理一下
            }
        }catch (Exception e){

        }

    }
    // 发送post请求
    // 重载
    public void post(String data) {
        //System.out.println("post ok");

    }

    // 测试
    public static void main(String[] args) {
        MzHttp mzhttp = new MzHttp("https://mz1.top");
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("uname", "Mz1");
        param.put("passwd", "123456");
        param.put("phone_num", "13337823843");
        //mzhttp.get();
        mzhttp.post(param);
        System.out.println(mzhttp.getText());
    }
}

posted @ 2021-09-03 21:28  Mz1  阅读(242)  评论(0编辑  收藏  举报