簡體   English   中英

Android網絡連接故障

[英]android network connection faliure

我很難將應用程序連接到互聯網並檢索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權限。

您需要移動連接到互聯網並將代碼提取到AsyncTask 這是由於NetworkOnMainThreadException 當應用程序嘗試在其主線程上執行聯網操作時,將引發此異常。

盡管可以使用StrictMode.ThreadPolicy解決方法,但最好不要這樣做。

這是docs的節選。

NetworkOnMainThreadException:-

僅針對面向Honeycomb SDK或更高版本的應用程序拋出此錯誤。 允許以較早版本的SDK為目標的應用程序在其主事件循環線程上進行聯網,但不建議這樣做。

有關更多信息,請參見此問題

因為您是在UI therad上執行此操作的。

嘗試這個:

公共類Main擴展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) {
            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();
        }
    });
}

我會建議您使用AsyncTask

做這個

ButtonClick上

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

RequestClient

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);

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM