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();
        }
    }

案例代码

相关推荐
长亭外的少年6 小时前
Kotlin 编译失败问题及解决方案:从守护进程到 Gradle 配置
android·开发语言·kotlin
建群新人小猿8 小时前
会员等级经验问题
android·开发语言·前端·javascript·php
1024小神10 小时前
tauri2.0版本开发苹果ios和安卓android应用,环境搭建和最后编译为apk
android·ios·tauri
兰琛10 小时前
20241121 android中树结构列表(使用recyclerView实现)
android·gitee
Y多了个想法10 小时前
RK3568 android11 适配敦泰触摸屏 FocalTech-ft5526
android·rk3568·触摸屏·tp·敦泰·focaltech·ft5526
NotesChapter11 小时前
Android吸顶效果,并有着ViewPager左右切换
android
_祝你今天愉快13 小时前
分析android :The binary version of its metadata is 1.8.0, expected version is 1.5.
android
暮志未晚Webgl13 小时前
109. UE5 GAS RPG 实现检查点的存档功能
android·java·ue5
麦田里的守望者江13 小时前
KMP 中的 expect 和 actual 声明
android·ios·kotlin
Dnelic-13 小时前
解决 Android 单元测试 No tests found for given includes:
android·junit·单元测试·问题记录·自学笔记