HttpURLConnection适用于模拟器,但不适用于设备

时间:2012-04-25 22:07:11

标签: android httpurlconnection

我正在尝试使用HttpURLConnection来从服务器获取一些XML。 这是我正在使用的代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    String myConn = this.getString(R.string.myConnection);
    HttpURLConnection httpConnection = null;
    InputStream in = null;
    try {
        URL mySite = new URL(myConn);
        URLConnection connection = mySite.openConnection();
        TextView tv = (TextView)this.findViewById(R.id.myTextView);
        httpConnection = (HttpURLConnection)connection;         

            in = httpConnection.getInputStream();

            String myString = convertStreamToString(in);
            tv.setText(myString);           

    } catch (IOException ex) {} catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally {
        httpConnection.disconnect();
        try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

在模拟器上,此代码有效,我可以在TextView上看到流...

在我的设备上,我看不到任何东西(3g连接)..

我错过了什么吗?

感谢

1 个答案:

答案 0 :(得分:-1)

使用AsyncTask您可以解决此问题。

相关问题