在通过网络获取数据时发生Android异常

时间:2017-12-12 07:07:48

标签: java android

我已经创建了一个Android应用程序并在模拟器上调试它,但它给了我一个异常android.os.NetworkOnMainThreadException

下面是远程访问数据的java代码。

  String filepath = datapath + "/tessdata/eng.traineddata";
       // AssetManager assetManager = getAssets();
        URL url = new URL("http://192.168.2.52/tessdata/eng.traineddata");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        connection.connect();
       // assetManager.open("tessdata/eng.traineddata");
        InputStream instream =  connection.getInputStream();
        OutputStream outstream = new FileOutputStream(filepath);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = instream.read(buffer)) != -1) {
            outstream.write(buffer, 0, read);
        }


        outstream.flush();
        outstream.close();
        instream.close();

        File file = new File(filepath);
        if (!file.exists()) {
            throw new FileNotFoundException();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我在AndroidManifest.xml

中添加了权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

0 个答案:

没有答案