Android 指定有线网或Wifi进行网络请求

时间: 2023-12-21 admin 维修知识

Android 指定有线网或Wifi进行网络请求

Android 指定有线网或Wifi进行网络请求

Android 指定有线网或Wifi进行网络请求

文章目录

  • Android 指定有线网或Wifi进行网络请求
    • 一、前言:
    • 二、指定网络通讯测试
      • 1、 窗口命令 ping -I 网络节点 IP
      • 2、Java 代码指定特定网络通讯
    • 三、指定特定网络的demo app 开发
      • 1、效果图:
      • 2、实际测试结果说明:
      • 3、获取不同网络ip地址的代码:
      • 4、demo代码下载地址

一、前言:

有些场景需要指定特定的网络进行通讯;
比如Wifi 和有线网同开的设备,指定某个网络进行通讯;或者某些指定网络进行通讯的场景。

最近刚好开发了Wifi 和有线网同开同联的需求,顺便提分享特定网络请求的代码。

Android11上修改有线网和wifi共存:

二、指定网络通讯测试

1、 窗口命令 ping -I 网络节点 IP

测试通过节点对应的网络访问某个ip

130|console:/ # 
130|console:/ # ping wwwbaidu
PING wwwbaidu (45.194.224.35) 56(84) bytes of data.
64 bytes from 45.194.224.35: icmp_seq=1 ttl=43 time=13.6 ms
64 bytes from 45.194.224.35: icmp_seq=2 ttl=43 time=13.4 ms
64 bytes from 45.194.224.35: icmp_seq=3 ttl=43 time=38.7 ms
64 bytes from 45.194.224.35: icmp_seq=4 ttl=43 time=13.5 ms
^C
--- wwwbaidu ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 13.452/19.851/38.744/10.908 ms
console:/ # 
console:/ # 
console:/ # ping -I eth0 www.baidu
PING www.a.shifen (157.148.69.80) from 192.168.31.174 eth0: 56(84) bytes of data.
64 bytes from 157.148.69.80: icmp_seq=1 ttl=46 time=15.0 ms
64 bytes from 157.148.69.80: icmp_seq=2 ttl=46 time=14.5 ms
64 bytes from 157.148.69.80: icmp_seq=3 ttl=46 time=15.2 ms
64 bytes from 157.148.69.80: icmp_seq=4 ttl=46 time=14.6 ms
^C
--- www.a.shifen ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 14.580/14.877/15.257/0.294 ms
console:/ # 
console:/ # ping -I wlan0 www.baidu
PING www.a.shifen (157.148.69.80) from 192.5.1.34 wlan0: 56(84) bytes of data.
64 bytes from 157.148.69.80: icmp_seq=1 ttl=41 time=478 ms
64 bytes from 157.148.69.80: icmp_seq=2 ttl=41 time=99.9 ms
64 bytes from 157.148.69.80: icmp_seq=3 ttl=41 time=89.0 ms
64 bytes from 157.148.69.80: icmp_seq=4 ttl=41 time=96.1 ms
^C
--- www.a.shifen ping statistics ---
5 packets transmitted, 4 received, 20% packet loss, time 4005ms
rtt min/avg/max/mdev = 89.084/191.015/478.886/166.248 ms
console:/ # 

这里可以看到有线网和wifi都是对外正常进行通讯的。
未指定-I 的情况使用的是默认的网络。

2、Java 代码指定特定网络通讯

通过Java代码设置指定网络进行通讯

private void testNetwork() {Log.i(TAG, "testNetwork");ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);NetworkRequest.Builder builder = new NetworkRequest.Builder();// 设置指定的网络传输类型// wifi: NetworkCapabilities.TRANSPORT_WIFI// 有线网络: NetworkCapabilities.TRANSPORT_ETHERNET//builder.addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET);// 设置感兴趣的网络功能builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);NetworkRequest request = builder.build();ConnectivityManager.NetworkCallback callback = new ConnectivityManager.NetworkCallback() {@Overridepublic void onAvailable(Network network) {super.onAvailable(network);Log.i(TAG, "已根据功能和传输类型找到合适的有线网络");Log.i(TAG, "testnet onAvailable network = " + network.toString());// 通过network.openConnection 来获取URLConnectiontry {HttpURLConnection urlConnection = (HttpURLConnection) network.openConnection(new URL(""));if (urlConnection != null) {int responseCode = urlConnection.getResponseCode();String responseMessage = urlConnection.getResponseMessage();Log.i(TAG, "testEthernetonAvailable responseCode = " + responseCode);Log.i(TAG, "testEthernet onAvailable responseMessage = " + responseMessage);InputStream inputStream = urlConnection.getInputStream();String result = new BufferedReader(new InputStreamReader(inputStream)).lines().parallel().collect(Collectors.joining("\n"));Log.i(TAG, "testEthernet onAvailable result = " + result);}} catch (IOException e) {Log.e(TAG, "testEthernet onAvailable error = " + e.getMessage());}connectivityManager.unregisterNetworkCallback(this);}};connectivityManager.registerNetworkCallback(request, callback);connectivityManager.requestNetwork(request, callback);
}

关键是NetworkRequest.Builder.addCapability 指定网络

三、指定特定网络的demo app 开发

1、效果图:

上图显示的有:


(1)wifi 和 有线网的 ip地址
(2)指定某个网络请求数据
(3)设置请求特定的网址
(4)返回请求的时间,网络的id,网址的html源码内容

这里的网络的id 是当前请求网络的 Network 对象的网络id值,同时 dumpsys connectivity 命令是可以看到的。

2、实际测试结果说明:

实际测试情况:

(1)当WiFi 和 有线网同时连接的情况
指定是没有作用的,请求网络使用的是高优先级的网络,这里是有线网网络。
通过 Network toString() 信息可以看到 当前连接网络的network id。(2)只开单一网络的情况
指定网络是有作用的;
如果开启有线网,指定WiFi 网络是无法进行数据请求的
如果开启Wifi,指定有线网是无法进行数据请求的
默认网络是可以正常请求网络数据的。

3、获取不同网络ip地址的代码:

可以通过代码查看Wifi 和有线网的 Ip地址

//getIpAddress,第二个参数是决定是获取的wifi的ip地址还是有线网的ip地址public static String getIpAddress(Context context, boolean isGetWifiIp) {Network network = null;if (isGetWifiIp) {network = getWlanNet(context);} else {network = getFirstEthernet(context);}if (network == null) {return "";}ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);final LinkProperties linkProperties = mConnectivityManager.getLinkProperties(network);if (linkProperties != null) {for (LinkAddress linkAddress : linkProperties.getLinkAddresses()) {InetAddress inetAddress = linkAddress.getAddress();if (inetAddress instanceof Inet4Address) {return inetAddress.getHostAddress();}}}return "";}//getFirstEthernetprivate static Network getFirstEthernet(Context context) {ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);final Network[] networks = mConnectivityManager.getAllNetworks();for (final Network network : networks) {NetworkInfo networkInfo = mConnectivityManager.getNetworkInfo(network);if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {return network;}}return null;}//getFirstWlanprivate static Network getWlanNet(Context context) {ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);final Network[] networks = mConnectivityManager.getAllNetworks();for (final Network network : networks) {NetworkInfo networkInfo = mConnectivityManager.getNetworkInfo(network);if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {return network;}}return null;}

通过上面的代码 getIpAddress 方法,是可以分别获取到Wifi 和有线网的 Ip的!

4、demo代码下载地址