Chrome generate two request - spring

In a spring boot application a link generate a pdf file.
Link in thymeleaf
<a th:href="#{/printings/bytesttype/compressions}" class="list-group-item list-group-item-action"><span th:text="#{compressions}">Compressions</span></a>
On the controller side
#GetMapping(value = "/printings/bytesttype/compressions")
public ResponseEntity<byte[]> getCompressionsReport() throws IOException, Exception {
return preparePdfReport(samplingFacade.getCompressionToPrint());
}
private ResponseEntity<byte[]> preparePdfReport(byte[] content) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String fileName = "report.pdf";
headers.setContentDispositionFormData(fileName, fileName);
headers.setCacheControl("no-cache, must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(content, headers, HttpStatus.OK);
return response;
}
Actually user click, a request is done.
After another request is done to open with extension
chrome-extension://oemmndcbldboiebfnladdacbdfmadadm/http://localhost:8080/printings/bytesttype/compressions
Is there a way to avoid that?
tried
Chrome sends two requests when downloading a PDF (and cancels one of them)
problem still exist

If you dont have to show PDF with the extension (browser inline) you can try adding a header to your HTTP Response as follows:
response.setHeader("Content-Disposition", "attachment; filename=report.pdf");

Related

How to read response with Content-Type text/plain;charset=UTF-8 using RestTemplate

I have an API (/get-sas-token) that is returning a response with Content-Type=text/plain;charset=UTF-8.
In Postman when I hit this API it returns as sig=PAd%2By7yzue0G%2FVeMKbwvR%2F%2B5a3X8CUTablCIhS3uCuk%3D&s
The code for this API is
#GetMapping("/get-sas-token/{containerName}")
public String getSASToken(#PathVariable("containerName") String containerName)
throws InvalidKeyException, URISyntaxException, StorageException {
CloudBlobContainer appcontainer = config.blobClient().getContainerReference(containerName);
return appConfiguration.generateSASToken(appcontainer);
}
My other microservice is trying to call this RestAPI using RestTemplate via a get request. The response I'm getting in Postman has instead of special characters like �������{J�J��t�\b�`$ؐ#������iG# some weird stuff. So I guess somethings wrong with the character encoding.
P.S : If I remove the Accept-Encoding(gzip, deflate, br) header from Postman it works.How can i get it working in my code
ResponseEntity<String> imageUrl = restTemplate.exchange(
fileServiceUrl + "/get-sas-token/" + containerReference, HttpMethod.GET, request, String.class);
logger.info("imageUrl body-------->>" + imageUrl.getBody());
It prints
imageUrl body-------->>?`I?%&/m?{J..................
I have tried all the possible soultions but nothing works for me
tried this::
template.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
ResponseEntity<Object> response = template.exchange(endpoint, method, entity,
Object.class);
Also this::
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Accept", "application/json");

Upload to google drive using The files get uploaded, but, only in the root and are always named "Untitled"

I am trying to upload files to Google drive using a REST API
Everything is working fine, but files are uploading into Google Drive only in the root, and with "Untitled" as their name.
public class UploadTODrive {
public static DriveFiles UploadFileTODrive(String accessToken, MultipartFile files) throws IOException {
RestTemplate restTemplate = new RestTemplate();
String requestUri = "https://www.googleapis.com/upload/drive/v2/files";
System.out.println("ContentType==============: " + files.getContentType());
byte[] s=files.getBytes();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", files.getContentType());
headers.setContentLength(0);
//headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.add("Authorization", "Bearer " + accessToken);
HttpEntity<byte[]> requestEntity = new HttpEntity<>(s, headers);
ResponseEntity<String> response = restTemplate.exchange(requestUri, HttpMethod.POST, requestEntity,
String.class);
System.out.println("=====>Response: " + response);
Gson gson = new Gson();
DriveFiles driveFiles = gson.fromJson(response.getBody(), DriveFiles.class);
return driveFiles;
}
}
Files are uploaded to google drive in two parts.
The first part is the meta data of the file, this being the name and the mimetype most often and occasionally containing a parent directory.
The second part is the upload of the actual file stream.
It seams that you are uploading the file stream but you have forgotten to post the file metadata. This is posted in the body of your request
This is your HTTP Post request. You need to figure out how to add a post body to this. This is the documentation link to the writable fields that you can post insert#request-body
ResponseEntity<String> response = restTemplate.exchange(requestUri, HttpMethod.POST, requestEntity,
String.class);
Update
found this with a bit of googling
RESTRequest1.AddBody('{"title": "Capture.jpg"}', TRESTContentType.ctAPPLICATION_JSON);

Spring Controller return static HTML site from any directory

I would like to return in my #Controller static HTML website that was generated by other process. Let's say that generated .html files are in /tmp/generated. I'm trying to read file and pass its content to ResponseEntity:
#GetMapping(value = "test")
ResponseEntity<String> test(#RequestParam("filename") String filename) throws IOException {
String content = new String(Files.readAllBytes(Paths.get("/tmp/generated/" + filename)), "UTF-8");
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_HTML);
return new ResponseEntity<String>(content, headers, HttpStatus.OK);
}
But when I open url in browser I get badly encoded html content (stating and ending with '"'):
"\u003chtml\u003e\n\u003chead\u003e\n \u003cmeta charset\u003d\"utf-8\" /\u003e\n \u003cmeta http-equiv\u003d\"X-UA-Compatible\" content\u003d\"IE\u003dedge\" /\u003e\n \u003cmeta name\u003d\"viewport\" content\u003d\"width\u003ddevice-width, initial-scale\u003d1\" /\u003e [.....]
If I add produces = MediaType.TEXT_HTML_VALUE to my #GetMapping annotation then I get 406 Not Acceptable error response (but no exception in my spring app)...
How to fix it?
I'm not sure why you are facing problems when using produces in your mapping.
I gave a quick try and it worked for me.
#GetMapping(value = "test", produces=MediaType.TEXT_HTML_VALUE)
public ResponseEntity<String> test(#RequestParam("filename") String filename) throws IOException {
String content = new String(Files.readAllBytes(Paths.get("/tmp/generated/" + filename)), "UTF-8");
return new ResponseEntity<String>(content, HttpStatus.OK);
}
Tested in Chrome browser:
File
NOTE: I tested this controller using SpringBoot v2.0.5.RELEASE
Cheers!
I have successfully build application with Spring Boot 1.5.2.RELEASE and it will return static HTML site from any directory
you can checkout here

How can I fix this issue, when file download in the browser, it change encoding in file, I used Spring boot

I used it code for response Excel byte[] to browser. But I have problem, because Spring boot encode file, and I got bad file than download from browser.
//This method returned response on controller
public ResponseEntity<ByteArrayResource>
returnAllTransactionAsExcel(TransactionSearchFilter
transactionSearchFilter) throws IOException {
List<Transaction> transactions =
getAllTransactions(transactionSearchFilter);
byte[] ourFile=writeIntoExcel(transactions);
//headers
HttpHeaders headers = new HttpHeaders();
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Content-Disposition", "attachment;
filename=list_transactions.xls");
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
return
ResponseEntity
.ok()
.headers(headers)
.contentLength(ourFile.length)
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.body(new ByteArrayResource(ourFile));
}
//This method on controller
#ApiOperation(value = "Retrieve all transactions in Excel")
#RequestMapping(value = "/allExcel", method = RequestMethod.POST,
produces "application/vnd.ms-excel")
public ResponseEntity<ByteArrayResource>
getAllTransactionsAsExcel(#RequestBody TransactionSearchFilter
transactionSearchFilter) throws IOException {
return returnAllTransactionAsExcel(transactionSearchFilter);
}
I solved my problem, all problem was in swagger-ui
https://github.com/webanno/webanno/issues/459

AngularJS Post request to Web service for downloading a file

I need to send JSON to a web service using HTTP POST method in AngularJS to download a file.
AngularJS:-
$http
.post(
'url',
'My Json data ')
.success(function(response) {
console.log('file downloading');
})
.error(
function(response) {
console
.log('Error while downloading file');
});
Spring Controller:-
#RequestMapping(value = "/url", method = RequestMethod.POST)
#ResponseBody
public void getfile(#RequestBody List<ABC> abc, HttpServletResponse response)
throws JRException, IOException, SQLException {
//My code here
response.reset();
response.setContentType("application/x-pdf");
response.setHeader("Content-disposition", "attachment; filename=ABC.pdf");
final OutputStream outStream = response.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint,outStream);
outStream.flush();
outStream.close();
I have to call this from angular using POST request. How to acheive so?
EDIT
I was able to meet the requirements by referring this thread.
please see this very helpful function to download a file using POST request. Function is dependant on jQuery . the implementation creates a html form inline with hidden field and then submit it

Resources