首页 > 解决方案 > 如何从 url 请求更新或下载 json 文件到本地目录?

问题描述

我正在尝试制作一个移动应用程序,我正在使用的数据是一个巨大的嵌套 JSON 对象,它是某些网站上的实时 API。我没有调用 URL 请求来获取数据,而是下载了 json 文件并将其存储在我的 android 资产文件夹中。由于数据如此庞大,所以我将其存储在本地资产文件夹中以避免请求延迟。问题是,我已经将它存储在本地,如果数据在网站上得到更新,它不会出现在我身上。我想做某种方法,应用程序用户可以自己更新数据。

public void updatingJSONFile(){
    HttpURLConnection urlConnection;
    InputStream in = null;
    try{

        //the url we wish to connect to
        URL url = new URL("my URL");
        //open the connnection to the specific url
        urlConnection = (HttpURLConnection) url.openConnection();
        //get the response from the server in the input stream
        in = new BufferedInputStream(urlConnection.getInputStream());

    }catch(IOException e){`enter code here`
        e.printStackTrace();
    }
    // convert the input stream to a string
    String response = convertStreamToString(in);
    // print the response to the android monitor/logcat
    System.out.print("Server response = " + response);

    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(response);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
}

标签: androidjson

解决方案


推荐阅读