首先需要添加以下模块库:

  1. okhttp3:用于进行网络请求。
  2. android.permission.ACCESS_WIFI_STATE:用于获取手机的MAC地址。

在AndroidManifest.xml文件中添加以下权限:

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

在build.gradle文件中添加以下依赖:

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.0'
}

在OnClick方法中添加以下代码:

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button:
            String ip = getIpAddress();
            String mac = getMacAddress();
            sendPostRequest(ip, mac);
            break;
    }
}

private String getIpAddress() {
    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
    return String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
}

private String getMacAddress() {
    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    return wifiInfo.getMacAddress();
}

private void sendPostRequest(String ip, String mac) {
    OkHttpClient client = new OkHttpClient();

    RequestBody requestBody = new FormBody.Builder()
            .add('ip', ip)
            .add('mac', mac)
            .build();

    Request request = new Request.Builder()
            .url("http://172.30.9.250:10000/portal_ylsy/login.do")
            .post(requestBody)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e("POST REQUEST", "Error: " + e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String responseData = response.body().string();
            Log.i("POST REQUEST", "Response: " + responseData);
        }
    });
}

在这里,我们使用了OkHttp3库来进行POST请求。首先,我们需要创建一个OkHttpClient对象来发送请求。然后,我们需要创建一个RequestBody对象,将IP和MAC地址添加到表单中。接下来,我们创建一个Request对象,将URL和RequestBody对象传递给构造函数。最后,我们使用enqueue()方法异步发送请求,并在回调函数中处理响应。

以上是完整的代码,希望对您有所帮助。

Android Studio 底部按钮点击事件:获取手机IP和MAC并发送POST请求

原文地址: https://www.cveoy.top/t/topic/mNMa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录