Android——网络请求

  • get 请求
java 复制代码
public static String doGeg() {
        String result = "";
        BufferedReader reader;
        try {
            // 1.建立连接
            HttpURLConnection httpURLConnection = null;
            String url = "https://www.baidu.com";
            URL requestUrl = new URL(url);
            httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.connect();

            // 2.获取二进制流
            InputStream inputStream = httpURLConnection.getInputStream();

            // 3.将二进制流包装
            reader = new BufferedReader(new InputStreamReader(inputStream));

            // 从Buffer reader中读取string字符串
            String line;
            StringBuilder builder = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append("\n");
            }

            if (builder.length() == 0) {
                return null;
            }
            result = builder.toString();
        } catch (Exception e) {
            Log.d("EEEE", "1");
            e.printStackTrace();
        }
        return result;
    }
  • post 请求
java 复制代码
public static boolean doPost(String utlStr) {
        HttpURLConnection urlConnection = null;
        OutputStream outputStream = null;
        boolean result = false;

        try {
            URL url = new URL(utlStr);

            // 1.打开连接
            urlConnection = (HttpURLConnection) url.openConnection();
            // 2.准备请求数据
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("userName", "zs");
            paramMap.put("pass", "123");
            String paramData = paramMapToString(paramMap);

            // 3.设置连接信息
            urlConnection.setRequestMethod("POST");
            urlConnection.setConnectTimeout(5000);
            urlConnection.setRequestProperty("Content-Length", String.valueOf(paramData.length()));

            // 设置conn可以向服务端输出的内容
            urlConnection.setDoOutput(true);

            // 4.获取输出流,并进行输出
            outputStream = urlConnection.getOutputStream();
            outputStream.write(paramData.getBytes());

            // 5.获取服务端的响应结果
            int code = urlConnection.getResponseCode();
            if (code == 200) {
                result = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

将Map转为字符串

java 复制代码
    public static String paramMapToString(Map<String, String> paramMap) {
        StringBuilder sb = new StringBuilder();
        Set<Map.Entry<String, String>> entries = paramMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            sb.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }
        // 去掉最后一个&
        sb.deleteCharAt(sb.length() - 1);

        return sb.toString();
    }

处理JSON

java 复制代码
    public static void handleJson(String jsonStr) {
        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
            String name = jsonObject.optString("name");
            Log.d("AAAA", name);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

案例代码

相关推荐
ModestCoder_29 分钟前
将一个新的机器人模型导入最新版isaacLab进行训练(以unitree H1_2为例)
android·java·机器人
robin_suli1 小时前
Spring事务的传播机制
android·java·spring
鸿蒙布道师2 小时前
鸿蒙NEXT开发对象工具类(TS)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
Harrison_zhu3 小时前
Ubuntu18.04 编译 Android7.1代码报错
android
CYRUS STUDIO5 小时前
Unidbg Trace 反 OLLVM 控制流平坦化(fla)
android·汇编·算法·网络安全·逆向·ollvm
扫地的小何尚5 小时前
NVIDIA工业设施数字孪生中的机器人模拟
android·java·c++·链表·语言模型·机器人·gpu
顾林海7 小时前
深度解析ArrayList工作原理
android·java·面试
安静的海岸_AI7 小时前
Android端WIFI/流量共存技术方案
android
_一条咸鱼_7 小时前
Android Compose 框架进度指示器深入剖析(五十二)
android
张风捷特烈8 小时前
Flutter 伪 3D 绘制#02 | 地平面与透视
android·flutter