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.
Related
I'm specifically trying to test the case where my application doesn't receive a Content-Length header from the server, so I've set up my code not to include that header, but for some reason Spring is including it anyway with a value of 0:
#RequestMapping(value = "/test", method = RequestMethod.HEAD)
public void headTest(HttpServletRequest request, HttpServletResponse response) {
response.addDateHeader("Date", System.currentTimeMillis());
response.addHeader("Accept-Ranges", "bytes");
response.addHeader("Content-Type", "video/mp4");
}
$ curl -I http://myserver.com:8600/test
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Date: Thu, 28 Jul 2022 01:05:11 GMT
Accept-Ranges: bytes
Content-Type: video/mp4
Content-Length: 0
How can I stop Spring from including this header?
Setting a header to null to effectively remove it from the response works for embedded Tomcat and might work for other servers:
response.setHeader("Content-Length", null);
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
I have the following jersey controller.
#POST
#ApiOperation(value = "", response = Certification.class)
public Response addCertification(#Valid CertificationRequest request) {
return Response.ok(certificationService.addCertification(request)).build();
}
I have then developed the following test using Mockito and SpringRunner.
#Test
public void givenValidToken_whenAddingCertification_thenCorrect() {
CertificationRequest certificationRequest = new CertificationRequest();
certificationRequest.setName("name");
Certification certification = new Certification();
when(certificationService.addCertification(certificationRequest)).thenReturn(certification);
given()
.contentType(ContentType.JSON)
.body(certificationRequest)
.when()
.post("/certifications")
.then()
.assertThat()
.statusCode(200)
.contentType(ContentType.JSON)
.log()
.all();
}
Written just like that, I receive the following error when it is executed.
HTTP/1.1 200
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: Fri, 26 Jun 2020 18:33:35 GMT
java.lang.AssertionError: 1 expectation failed.
Expected content-type "JSON" doesn't match actual content-type "".
On the other hand, if I add null in place of certificationRequest and send an empty body in RestAssured , it works fine.
Why does it return an empty body when sent with a request body ?
At least one of your problems is the following:
when(certificationService.addCertification(certificationRequest)).thenReturn(certification);
You need a Matcher instead of certificationRequest. If you want to match any Request you can use ArgumentMatchers.any(). If you want to check for a specific Request you can use ArgumentMatchers.eq(certificationRequest). Note that ArgumentMatchers.eq(...) will only work if you've provided a valid equals method (Or if you pass exactly the same argument, afair).
So for example:
when(certificationService.addCertification(ArgumentMatchers.eq(certificationRequest))).thenReturn(certification);
If that doesn't solve your problem, I would try to print the response and check what you get there.
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 trying to test my app using rest assured, I am using spring security
This is sthe code
RestAssured.baseURI = "http://myapp-breakid.rhcloud.com/";
RestAssured.port = 80;
Response response = expect().given().auth().form("admin", "sababa1.",springSecurity().withLoggingEnabled(new LogConfig())).
when().get("login");
but this is the response:
HTTP/1.1 302 Found
Date: Mon, 01 Dec 2014 20:38:57 GMT
Server: Apache-Coyote/1.1
Location: http://myapp-breakid.rhcloud.com/index
Content-Length: 0
Set-Cookie: JSESSIONID=32E5F577A6885826DF17ACEE4B3386AF; Path=/; HttpOnly
Accept-Ranges: none
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/plain
What am I missing ?
You don't need to go to the login page to login, REST Assured does this automatically. This works:
RestAssured.baseURI = "http://myapp-breakid.rhcloud.com";
RestAssured.authentication = form("admin", "sababa1.", springSecurity());
get("/index").prettyPrint();
What happens here is that form authentication is automatically performed before each request. If it's important to use the same session in multiple requests you should use a session filter. For example:
RestAssured.baseURI = "http://myapp-breakid.rhcloud.com";
SessionFilter sessionFilter = new SessionFilter();
given().
auth().form("admin", "sababa1.", springSecurity()).
filter(sessionFilter).
when().
get("/index");
// Session filter will automatically capture the session id and you can reuse it in subsequent requests.
given().
filter(sessionFilter).
when().
get("/another_protected_resource").
then().
statusCode(200);
You can also get the sessionId from the SessionFilter and use it like this:
given().
sessionId(sessionFilter.getSessionId()).
when().
get("/another_protected_resource").
then().
statusCode(200);