创建一个从网址读取文本的Android应用程序

时间:2013-10-09 03:18:33

标签: java android http url text

我找到答案了 在主要活动的“onCreate”方法中包含以下两行:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();   
StrictMode.setThreadPolicy(policy); 

我创建了一个Android应用程序,它将从URL读取文本并在屏幕上显示文本。当我的输入为“http://web.njit.edu/~halper/it114/l2d.txt”时它会崩溃,但当我的输入为“http://web.njit.edu/~halper/it114/l2d.txt”时什么也不做。我尝试将android.permission.INTERNET添加到Manifest.xml中,我仍然得到相同的结果     致命异议:主要     java.lang.IllegalStateException:无法执行活动的方法
    引起:java.lang.reflect.InvocationTargetException
    引起:android.os.NetworkOnMainThreadException
非常感谢你的时间

public void enter(View v) {

EditText input = (EditText) findViewById(R.id.edit_file);
TextView tv = (TextView) findViewById(R.id.text_main);

try {
URL url = new URL( input.getText().toString() );            
Scanner scan = new Scanner( url.openStream() );
while( scan.hasNext() ) 
tv.append( scan.nextLine() );   
}

catch(MalformedURLException e) { e.printStackTrace(); }
catch(IOException e) {e.printStackTrace();}
}

2 个答案:

答案 0 :(得分:0)

这对我有用:

    public String getTextFromTheMagicKingom() throws ClientProtocolException, IOException {
        String url = "http://web.njit.edu/~halper/it114/l2d.txt";
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        HttpResponse response = client.execute(request);
        BufferedReader rd = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        return result.toString();
    }

请更正评论中的格式。祝你有愉快的一天._。/

答案 1 :(得分:0)

Caused by: android.os.NetworkOnMainThreadException

由于HoneyComb我们不再允许在UI线程上进行网络调用,因为它们可能会变慢,在服务器上等待时挂起UI会很愚蠢。您需要将网络代码放在单独的Thread中,或使用AsyncTask或Volley等库。

如果这只是为了测试一下,那么你也可以转为StrictMode这是不允许从该线程进行网络访问的......

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); //Disabling StrictMode is not recommended. It is much better to make Asynchronous network calls...

您应该已经发布了发出网络请求的代码。您似乎正在为自己做练习,因此我建议您在获得响应时使用Thread并使用其runOnUiThread()方法。 AsyncTask具有比您需要的功能更多的功能......