I am using spring boot application to download a jasper file, which is downloaded in my system, on browser. The code that I have written is:
#GetMapping("/download")
public ResponseEntity downloadFileFromLocal(HttpServletResponse response) throws JRException, SQLException, IOException {
Path path = Paths.get(System.getProperty("user.home") + "//downloads//" + "fileName.pdf");
Resource resource = null;
try {
resource = new UrlResource(path.toUri());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/download"))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
This code is working perfectly fine and my file is being downloaded on browser when I try this code in a simple application i.e. practice approach. However, when I try to download the file in my main application with the same code then nothing happens. I am not sure what is stopping browser to download my pdf file in browser. The expected result is:
I think there is some problem with the response Headers.
Following is the response header for my Practice application file:
Accept-Ranges: bytes
Connection: keep-alive
Content-Disposition: attachment; filename="Daily%20Report%20For%20Site_ID%201.pdf"
Content-Length: 2869
Content-Type: application/download
Date: Mon, 27 Dec 2021 10:48:24 GMT
Keep-Alive: timeout=60
And for main application, response headers are:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Mon, 27 Dec 2021 11:28:33 GMT
Expires: 0
Pragma: no-cache
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Related
I am using
id 'org.springframework.boot' version '2.6.1'
Following is the code snippet I am using for throwing the exception
catch(Exception e){
System.out.println(e.getLocalizedMessage());
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, "something went wrong",e);
}
In response, we are getting 400 without a response body
* upload completely sent off: 100 out of 100 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 400
< Vary: Origin
< Vary: Access-Control-Request-Method
< Vary: Access-Control-Request-Headers
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Length: 0
< Date: Thu, 27 Oct 2022 14:43:38 GMT
< Connection: close
<
* Closing connection 0
UPDATE: application.properties has the following config
server.error.include-message=always
What am I missing?
Starting from 2.3, Spring Boot doesn't include an error message on the default error page. The reason is to reduce the risk of leaking information to a client.
To change the default behavior, you can set the server.error.include-message property:
server.error.include-message=always
Source:
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default-error-pages-content
The endpoint is in a RestController with this signature:
#PostMapping(value = "/unclaim")
#Operation(summary = "Unclaim Tasks ")
public BaseResponse<String> claimTasks(
#RequestParam(required = true, name = "taskIds") Long taskIds[]
)
{
If I use Soap ui to the correct URL ( I know I got that right, b/c if I append another character to it, I get a 404 ) I send this payload:
{
taskIds: [ 444, 34, 55 ]
}
Doing this in SoapUI and Postman both give 400s and no explanation :
HTTP/1.1 400
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Set-Cookie: JSESSIONID=C18701F799961FEECF967457574EB914; Path=/tlmapi; HttpOnly
Content-Length: 0
Date: Fri, 02 Sep 2022 16:11:44 GMT
Connection: close
But going to the swagger-ui.html page for this controller lets me construct a request that works :
So what's the difference ? Or is there a way to see the payload that swagger is sending?
Turns out that I accidentally was using the #RequestParam annotation on the list, instead of #RequestBody. Further, the param was Required, so spring rejected it and ignored my Json payload from SoapUI and Postman.
Hope this helps someone not waste a couple of hours...
I have created an application which uses spring session. When I make a call to api which needs to be authenticated I am getting an error, which is fine but also application generates a session id. Is it a correct behaviour?
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0HTTP/1.1 401 Unauthorized
X-Powered-By: Express
Access-Control-Allow-Origin: *
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
cache-control: no-cache, no-store, max-age=0, must-revalidate
pragma: no-cache
expires: 0
x-frame-options: DENY
set-cookie: SESSION=SESSION_ID; Path=/; HttpOnly
content-length: 0
date: Fri, 09 Aug 2019 17:04:46 GMT
connection: close
My authorization method looks which is called after log in:
public void authorize(final String authorizationCode, final HttpServletRequest request) {
log.info("Logging...");
final HttpSession httpSession = request.getSession();
httpSession.setAttribute("token", token);
httpSession.setAttribute("account_id", accountId);
httpSession.setAttribute("user_id", userId);
}
What is more in application.properties I set server.servlet.session.cookie.secure=true and still in cookie is only httpOnly.
I have a ajax request to a spring security backend. What happens for some reason is that .then doesn't occur ever. What I found out is that .fail occurs on every request, even though the request goes through, the login on the backend works and it returns a response with status code 200. So what defines a jqXHR as failed and what do I need to add in the response so it works as it should?
Here is my ajax request:
// Creates request object
function makeRequest(method, module, endpoint) {
return req = {
method,
url: serverBaseUrl + module + '/' + endpoint
};
}
// Function to return POST promise
function post (module, endpoint, data) {
let req = makeRequest('POST', module, endpoint);
req.data = data;
return $.ajax(req);
}
And here is the response I get from my spring security setup:
HTTP/1.1 200
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Wed, 28 Mar 2018 01:02:20 GMT
Expires: 0
Pragma: no-cache
Set-Cookie: JSESSIONID=8D6265E912D5DFCF418238F18586AFE1; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
After all my problem was in my $.ajax request. I had a dataType parameter added as application/json. That seems to be not valid. Found it out when i printed the error from the request when it failed. Got the answer from here:
jquery ajax call return JSON parsing error
I am facing this exception when receiving HttpWebResponse for my WindowsPhone app. How am I supposed to fix this. It happens very often but I need to make sure my app doesn't crash if it happens. Please have a look at the screenshot.
My expected response is
Headers:-
HTTP/1.1 500 Internal Server Error
Date: Wed, 28 Nov 2012 06:41:24 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Keep-Alive: timeout=30
Set-Cookie: ...........; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Internal Server Error:
Json:-
{"status":0,"error_code":1001,"data":{"msg":"Something went wrong. Please try again later. [error code 1001]"}}
It also shows in the InnerException the message as Specified value has invalid HTTP Header characters.
Parameter name: name
Please help. I don't know why webRequest.EndGetResponse(asynchronousResult) is not able to read the response. Is there an alternative?
UPDATE
to start the request:
_webRequest.BeginGetRequestStream(new AsyncCallback(GetReqeustStreamCallback), _webRequest);
private void GetReqeustStreamCallback(IAsyncResult asynchronousResult)
{
if ((!ReqIdEnabled || Network.RequestUniqueId == this.RequestUniqueId))
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
using (Stream postStream = webRequest.EndGetRequestStream(asynchronousResult))
{
// Add the post data to the web request
postStream.Write(_postDataInBytes, 0, _postDataInBytes.Length);
//postStream.Dispose();
}
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
try
{
//**throws Exception here when my server returns 503/500 and is not caught by the catch block below**
using (HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult))
{
ReadResponse(response);
}
}
catch (WebException ee)
{
}
}
Put a breakpoint in your catch block, and look at the lower level stacks, and look for System.Net.ni.dll!System.Net.WebHeaderCollection.this[string].set(string name, string value).
In the local variables, you can see for which particular value, the parse is failing.
For me, It was Google App Engine's custom User-Agent header which was creating the problem.