(AS笔记)Android的原生网络请求工具类——亲测可用

目录

一、前言

二、后端

三、Android端

        (1)HTTP限制访问

                ——network_security_config.xml

                ——AndroidManifest.xml

        (2)XML页面布局

        (3)HttpURLConnection工具类代码

        (4)MainActivity代码

四、效果测试

五、总结


一、前言

        公司要求使用原生方式请求后端API接口(SpringBoot),在此做个记录。


二、后端

        使用Mybatis-Plus查询MySQL单条数据,返回JSON格式到Android端。后端Controller代码如下:

    @ResponseBody
    @PostMapping(value = "/patch")
    public AdConfigBean selectConfigByPkgName(@RequestParam("gkpn") String pkgName) {
        return adconfigService.getOne(new QueryWrapper<AdConfigBean>()
                .select("*")
                .eq("pkg_name", pkgName), false);
    }

三、Android端

        (1)HTTP限制访问

        Android对HTTP协议的请求已经不支持了,需要进行放行配置。先创建XML,再到AndroidManifest.xml配置文件中引用。

                ——network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true"/>
</network-security-config>

                ——AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.demo">

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:usesCleartextTraffic="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Demo"
        tools:targetApi="n">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

        (2)XML页面布局

        布局为两个控件,单击按钮,请求成功,文本框展示后端返回的JSON数据。

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

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true" />

    <Button
        android:text="发送POST"
        android:id="@+id/btn_sendPost"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

        (3)HttpURLConnection工具类代码

public class NetworkUtil {

    public static String doGet(String urlPath) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(urlPath).openConnection();
            conn.setRequestMethod("GET");
            if (200 == conn.getResponseCode()) {
                return new BufferedReader(new InputStreamReader(conn.getInputStream())).readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "{ \"success\": false,\n   \"errorMsg\": \"后台服务器开小差了!\",\n     \"result\":{}}";
    }

    public static String doPost(String urlPath, HashMap<String, String> paramsMap) {

        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(urlPath).openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            StringBuilder result = new StringBuilder();
            for (HashMap.Entry<String, String> entity : paramsMap.entrySet()) {
                result.append("&").append(entity.getKey()).append("=").append(entity.getValue());
            }
            conn.getOutputStream().write(result.substring(1).getBytes());
            if (200 == conn.getResponseCode()) {
                return new BufferedReader(new InputStreamReader(conn.getInputStream())).readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "{ \"success\": false,\n   \"errorMsg\": \"后台服务器开小差了!\",\n     \"result\":{}}";
    }
}

        (4)MainActivity代码

public class MainActivity extends AppCompatActivity {

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

    }

    private void initView() {
        TextView tvShow = findViewById(R.id.tv_show);
        Button btnSendPost = findViewById(R.id.btn_sendPost);
        btnSendPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap<String, String> paramsMap = new HashMap<>();
                paramsMap.put("gkpn", "com.time.hxzbyx.meta");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String resultJson = NetworkUtil.doPost("http://www.wugua.com.cn/patch", paramsMap);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvShow.setText(resultJson);
                                Log.i("resultJson", resultJson);
                            }
                        });
                    }
                }).start();
            }
        });
    }
}

四、效果测试


五、总结

仅自己学习记录,如有错误,敬请谅解~,谢谢~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

电竞丶小松哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值