我的活动中有一段代码(我从模拟器开始)

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView txt=(TextView)this.findViewById(R.id.lbl);
    try {

            URL url = new URL("http://localhost/test.json");
            URLConnection urlconnection = url.openConnection();
            long l = urlconnection.getContentLength();

            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            StringBuffer buffer=new StringBuffer();
            while ((line = in.readLine()) != null)
            {
               buffer.append(line);
            }
            in.close();
            System.out.println("bufer="+buffer.toString());
            txt.setText(buffer.toString());


        } catch (Exception exc) {

           exc.printStackTrace();

        }
}


我的清单看起来像

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="test_android.test"
      android:versionCode="1"
      android:versionName="1.0">


    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".test_android"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

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


我的www目录中有wamp服务器和test.json,但始终会收到连接被拒绝的错误。怎么了 ?

最佳答案

在您的URL中,将“ localhost”替换为10.0.2.2

该IP是映射到localhost的特殊仿真器

编辑:
有关更多信息,请参见:http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking

07-24 09:49