Search code examples
restspring-mvcresttemplate

Is it possible to use RestTemplate on desktop instead of Android?


I encountered an error when I was trying to upload a file from my laptop to my server.

Exception in thread "main" java.lang.NoClassDefFoundError: android/os/Build$VERSION

I searched the error code and found an answer that suggesting I should run my code on an Android device, but what if I run my code on my laptop. Is it possible to create a RestTemplate standalone program running on desktop?

server side code:

@RequestMapping(value="/upload", method=RequestMethod.POST)
public String handleUpload(String filename, MultipartFile file) throws IOException {
    if(!file.isEmpty()) {
        File saveFile = new File(rootPath + "\\" + filename);
        saveFile.createNewFile();

        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(saveFile));

        FileCopyUtils.copy(file.getInputStream(), bufferedOutputStream);

        bufferedOutputStream.close();

        return "uploaded successfully";
    } else {
        return "failed";
    }
}

client side code:

public static void main( String[] args )
{
    String url = UPLOAD_URL;  
    String filePath = PATH + "\\204375-106.jpg";  

    SimpleClientHttpRequestFactory httpRequestFactory = new SimpleClientHttpRequestFactory();

    RestTemplate rest = new RestTemplate(httpRequestFactory);  
    FileSystemResource resource = new FileSystemResource(new File(filePath));  
    MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();  
    param.add("file", resource);  
    param.add("filename", "204375-106.jpg");  

    String string = rest.postForObject(url, param, String.class);  
    System.out.println(string);
}

Solution

  • For using RestTemplate on desktop environment you'll need the spring-web library: http://mvnrepository.com/artifact/org.springframework/spring-web/

    The name of the packages and classes are the same, so you can reuse your code.