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

案例代码

相关推荐
脚大江山稳9 分钟前
单独为mysql数据库的某个库创建用户
android·数据库·mysql
吉哥机顶盒刷机17 分钟前
XDBL安卓玩机刷机工具V2.8_解压缩版
android·智能手机·电脑
XiaoLeisj2 小时前
Android 广播机制实战:从系统广播监听、自定义登录通知到有序广播分发
android
urkay-2 小时前
Android 图片轮廓提取与重叠轮廓合并处理
android·算法·iphone
2501_916008892 小时前
2026 iOS 证书管理,告别钥匙串依赖,构建可复制的签名环境
android·ios·小程序·https·uni-app·iphone·webview
KevinCyao3 小时前
Go短信营销接口示例代码:Golang高并发调用营销短信接口的实现方案与代码分享
android·前端·网络·golang·前端框架
xiangxiongfly9155 小时前
Android 绘制流程源码分析
android·layout·measure·绘制流程·draw
进击的cc5 小时前
Android Kotlin:高阶函数与Lambda简化回调地狱
android·kotlin
1175 小时前
Android资源类型与常用的四种布局资源
android
常利兵5 小时前
Android 集合探秘:ArrayMap 与 SparseArray 的奇妙之旅
android·算法·哈希算法