Заголовок в URL-ссылку Android - PullRequest
0 голосов
/ 25 апреля 2020

У меня есть метод на сервере Spring, который требует токен пользователя, чтобы разрешить загрузку ресурса. Ресурс отправляется по URL в TextView. Когда я нажимаю на URL, открывается браузер, но, очевидно, без добавления заголовка. Как добавить заголовок с токеном к моему запросу? Или как я могу обработать это событие веб-браузера, чтобы вызвать мою собственную функцию с добавленным заголовком?

Я провел много исследований, но не смог найти ответ.

Вот мой метод / download на сервере Spring

@RequestMapping(value = "/download/{name:.+}", method = RequestMethod.GET)
    public HttpEntity<?> downloadFile (@RequestHeader("token") String token,
                                       @PathVariable("name") String name,
                                       final HttpServletRequest request, final HttpServletResponse response) throws IOException {

        if (tokenRepository.findByKeyVal(token) == null) {
            return null;

        }

        User userFrom = userRepository.findByToken(token);
        if(name.contains("_"+ userFrom.getId() +"_")){

         //  files names are saved in timestap + _user1+_user2 format//
            Resource resource;
            Path path = Paths.get(uploadDir + name);
            try {
                resource = new UrlResource(path.toUri());
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return null;
            }

            // Try to determine file's content type
            String contentType = null;
            try {
                contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
            } catch (IOException ex) {
                System.out.println("Could not determine file type.");
            }

            // Fallback to the default content type if type could not be determined
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        }
        else return new ResponseEntity<String>("Unauthorized", HttpStatus.UNAUTHORIZED);

    }
...