简体   繁体   中英

How to read a file from URL using Spring Controller?

We have a JSON Schema definition file hosted in a server and accessible via an URL. My Spring Controller, needs to validate the incoming JSON data (from an Ajax Call) against this schema.

Given the URL (like.. http://myservices.json.apiOneSchema.json ) of the schema definition file, How can i read this schema definition from my Spring Controller ?

Spring provides Resource class using which it can be done

 public static void main( String[] args )
    {
        ApplicationContext appContext = 
           new ClassPathXmlApplicationContext(new String[] {"If-you-have-any.xml"});

        Resource resource = 
           appContext.getResource("http://www.common/testing.txt");

    try{
          InputStream is = resource.getInputStream();
          BufferedReader br = new BufferedReader(new InputStreamReader(is));

          String line;
          while ((line = br.readLine()) != null) {
             System.out.println(line);
          } 
          br.close();

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

    }

The above snippet does exactly what you require. Also once you read the Resource you can use any binding to directly convert them to your POJO. The above is just an example of how you can read it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM