Android HTTP 连接

2022-01-19 00:00:00 sockets network-programming android java

谁能告诉我为什么这在 Android 模拟器中不起作用?从浏览器我可以访问并且服务器是内部的.我能想到的只是我的应用缺少一些配置,因此它可以访问网络层.

Can anybody tell my why this doesn't work in the Android emulator? From the browser I have access and the server is internal. All I can think of is that I'm missing some configuration on my app so it can access the network layer.

try {
    InetAddress server = Inet4Address.getByName("thehost");
    //Doesn't work either
    //or InetAddress server2 = Inet4Address.getByAddress(new String("192.168.1.30").getBytes());

    if(server.isReachable(5000)){
        Log.d(TAG, "Ping!");
    }

    Socket clientsocket = new Socket(server, 8080);
} catch (UnknownHostException e) {
    Log.e(TAG, "Server Not Found");
} catch (IOException e) {
    Log.e(TAG, "Couldn't open socket");
}

抛出 UnknownHostException

谢谢

推荐答案

就配置而言,您需要从应用程序访问 Internet 的唯一设置是 INTERNET 权限,通过添加以下行启用 在应用程序清单中的应用程序标签之外.

As far as configuration goes, the only setting you should need to access the Internet from your application is the INTERNET permission, enabled by adding the following line outside the Application tags within your application Manifest.

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

所以清单将遵循这个一般结构

So the manifest would follow this general construction

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.apis">    
  <uses-permission android:name="android.permission.INTERNET" />
  <application 
    android:name="MyApplication"    
    android:label="@string/application_title"
    android:icon="@drawable/my_icon">
    [ .. Your Activities go here ]
  </application>
</manifest>

相关文章