2

我有一个下载文件的活动,并且在执行该活动一段时间后,我在 onPostExecute() 上收到了 NetworkOnMainThreadException。该文件也没有完全下载。我找不到我错的地方。这是我的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity1);

    RetrieveFeedTask download = new RetrieveFeedTask();
    download.execute();
}

class RetrieveFeedTask extends AsyncTask<String, Void, InputStream> {

    private Exception exception;

    protected InputStream doInBackground(String... urls) {
        try {
             OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                  .url(URL)
                  .build();

              Response response = client.newCall(request).execute();
              InputStream asd = response.body().byteStream();
              System.out.println(asd + " vaslisiss");
                          return asd;
        } catch (Exception e) {
            System.out.println("helloooo");
            this.exception = e;;
            return null;
        }
    }

    protected void onPostExecute(InputStream feed) {
        Log.e("mactibiti", "exception", exception); 
        // TODO: do something with the feed
        if(exception == null)
            System.out.println("asdasdasdasdasdasdads");
        try{
        File file = new File(Environment.getExternalStorageDirectory() + "/downloaded_file.xml");
        FileOutputStream fileOutput = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ( (bufferLength = feed.read(buffer)) > 0 ) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        //close the output stream when complete //
        fileOutput.close();
        feed.close();
        }
        catch(Exception e){
            Log.e("filex", "ioexc", e);
        }

    }
}}
4

1 回答 1

3
protected void onPostExecute(InputStream feed) {

feedInputStream您从 Http 调用中读取的内容

于 2014-08-01T15:49:00.883 回答