0

我很难将应用程序连接到 Internet 并检索 html 源。一直在寻找解决方案,但没有找到。希望有人能帮忙。这是我的代码:

public class Main extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final EditText et = (EditText) findViewById(R.id.editText1);
        final Button b = (Button) findViewById(R.id.button1);
        final TextView tv = (TextView) findViewById(R.id.textView1);

        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                try {
                    URL url=null;
                    url = new URL(et.getText().toString());
                    URLConnection conn = url.openConnection();
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        tv.append(line);
                    }

                } catch (Exception e) {

                }

            }
        });
    }

我还添加了 INTERNET 权限..

4

3 回答 3

1

您需要将连接到 Internet 并将数据提取到AsyncTask. 这是因为NetworkOnMainThreadException. 当应用程序尝试在其主线程上执行网络操作时,将引发此异常。

尽管使用 有一种解决方法StrictMode.ThreadPolicy,但强烈建议不要这样做。

这是docs的摘录。

NetworkOnMainThreadException:-

这仅针对面向 Honeycomb SDK 或更高版本的应用程序抛出。允许以早期 SDK 版本为目标的应用程序在其主事件循环线程上进行网络连接,但非常不鼓励这样做。

有关更多信息,请参阅此问题

于 2013-09-24T11:51:55.343 回答
0

因为您是在 UI therad 上执行此操作的。

尝试这个:

公共类主要扩展活动{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final EditText et = (EditText) findViewById(R.id.editText1);
    final Button b = (Button) findViewById(R.id.button1);
    final TextView tv = (TextView) findViewById(R.id.textView1);

    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Thread th = new Thread() {
                @Override
                public void run() {
                    try {

                        URL url=null;
                        url = new URL(et.getText().toString());
                        URLConnection conn = url.openConnection();
                        BufferedReader reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                        String line = "";
                        while ((line = reader.readLine()) != null) {
                        tv.append(line);
                    }

                } catch (Exception e) {

                }
            }
        };
        th.start();
        }
    });
}
于 2013-09-24T11:56:43.550 回答
0

我会建议你使用AsyncTask

做这个

ButtonClick 上

RequestClient reqClient = new RequestClient(ActivityName.this);
String AppResponse = null;
AppResponse = reqClient.execute().get();

请求客户端

public class RequestClient extends AsyncTask<String, Void, String> {
    Context context;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected String doInBackground(String... params) {
        try {
            HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
            HttpGet httpget = new HttpGet("http://yoururl.com"); // Set the action you want to do
            HttpResponse response = httpclient.execute(httpget); // Executeit
            HttpEntity entity = response.getEntity(); 
            InputStream is = entity.getContent(); // Create an InputStream with the response
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) // Read line by line
            sb.append(line + "\n");

            String resString = sb.toString(); // Result is here

            is.close(); // Close the stream
            } catch (Exception e) {
            Log.d("ANDRO_ASYNC_ERROR", "Error is " + e.toString());
        }
        Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
        client.getConnectionManager().shutdown();
        return responseString.trim();
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

    }
}
于 2013-09-24T11:57:05.477 回答