I am trying to run this script for rest-assured, the last line uses a hamcrest assertion to validate the response body:
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class Basics {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Validate Add location API
// Setting up base URI
RestAssured.baseURI = "https://rahulshettyacademy.com";
//given : all inputs wrapped under given method // when : hit the API // then : validate the response
//add location
String response = given().log().all().queryParam("key", "qaclick123")
.header("Content-Type","application/json")
.body(payLoad.addLocation())
.when().post("/maps/api/place/add/json")
.then().assertThat().statusCode(200)
.body("scope", equalTo("APP"))
.header("Server",("Apache/2.4.41 (Ubuntu)"))
.extract().response().asString();
System.out.println(response);
//using JasonPath for parsing json
JsonPath js = new JsonPath(response);
String place_id = js.getString("place_id");
System.out.println(place_id);
//update location
given().log().all().queryParam("key","qaclick123")
.header("Content-Type","application/json")
.body("{\n" +
"\"place_id\":\""+place_id+"\",\n" +
"\"address\":\"70 Summer walk, USA\",\n" +
"\"key\":\"qaclick123\"\n" +
"}")
.when().put("/maps/api/place/add/json")
.then().log().all().assertThat()
.statusCode(200).body("msg",equalTo("Address successfully updated"));
}
}
It goes all well untill the last assertion to validate the response body, at the other place with the POST request the assertion is validating the response body but in the PUT request throws me this error:
Request method: POST
Request URI: https://rahulshettyacademy.com/maps/api/place/add/json?key=qaclick123
Proxy: <none>
Request params: <none>
Query params: key=qaclick123
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Content-Type=application/json
Cookies: <none>
Multiparts: <none>
Body:
{
"location": {
"lat": -38.383494,
"lng": 33.427362
},
"accuracy": 50,
"name": "Frontline house",
"phone_number": "(+91) 983 893 3937",
"address": "29, side layout, cohen 09",
"types": [
"shoe park",
"shop"
],
"website": "http://google.com",
"language": "English-IN"
}
{"status":"OK","place_id":"e50a637ebdf651c6808204513eedadd1","scope":"APP","reference":"ef6cc67ffac92ea58e901ee1bfe02bf5ef6cc67ffac92ea58e901ee1bfe02bf5","id":"ef6cc67ffac92ea58e901ee1bfe02bf5"}
e50a637ebdf651c6808204513eedadd1
Request method: PUT
Request URI: https://rahulshettyacademy.com/maps/api/place/add/json?key=qaclick123
Proxy: <none>
Request params: <none>
Query params: key=qaclick123
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Content-Type=application/json
Cookies: <none>
Multiparts: <none>
Body:
{
"place_id": "e50a637ebdf651c6808204513eedadd1",
"address": "70 Summer walk, USA",
"key": "qaclick123"
}
HTTP/1.1 200 OK
Date: Thu, 10 Nov 2022 16:56:27 GMT
Server: Apache/2.4.41 (Ubuntu)
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST
Access-Control-Max-Age: 3600
Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With
Content-Length: 0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json; charset=UTF-8
Exception in thread "main" java.lang.IllegalArgumentException: The JSON input text should neither be null nor empty.
at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:483)
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:73)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorSite.java:108)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:58)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:263)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:277)
at io.restassured.internal.path.json.ConfigurableJsonSlurper.parseText(ConfigurableJsonSlurper.groovy:80)
at io.restassured.internal.path.json.ConfigurableJsonSlurper$parseText.call(Unknown Source)
at io.restassured.internal.ContentParser.parse(ContentParser.groovy:42)
at io.restassured.internal.ContentParser$parse.call(Unknown Source)
at io.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure.validate(ResponseSpecificationImpl.groovy:497)
at io.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure$validate$1.call(Unknown Source)
at io.restassured.internal.ResponseSpecificationImpl.validateResponseIfRequired(ResponseSpecificationImpl.groovy:696)
at io.restassured.internal.ResponseSpecificationImpl.this$2$validateResponseIfRequired(ResponseSpecificationImpl.groovy)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at org.codehaus.groovy.runtime.callsite.PlainObjectMetaMethodSite.doInvoke(PlainObjectMetaMethodSite.java:43)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:198)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:62)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:185)
at io.restassured.internal.ResponseSpecificationImpl.body(ResponseSpecificationImpl.groovy:270)
at io.restassured.specification.ResponseSpecification$body$1.callCurrent(Unknown Source)
at io.restassured.internal.ResponseSpecificationImpl.body(ResponseSpecificationImpl.groovy:117)
at io.restassured.internal.ValidatableResponseOptionsImpl.body(ValidatableResponseOptionsImpl.java:244)
at Basics.main(Basics.java:50)
Please help me understand what am I missing here
URL of PUT request should be
https://rahulshettyacademy.com/maps/api/place/update/json?key=qaclick123
You used URL of POST request for PUT request.
Related
I am having a bit of an issue with logging my headers.
Here is my class that implements interceptor:
public class AuthInterceptor implements Interceptor {
private SessionManagement sessionManagement;
public AuthInterceptor(Context ctx) {
this.sessionManagement = new SessionManagement(ctx);
}
#NonNull
#Override
public Response intercept(#NonNull Chain chain) throws IOException {
Request request = chain.request();
Request.Builder requestBuilder = request.newBuilder();
// if token saved, add to request
String token = sessionManagement.getSessionToken();
if (token != null) {
requestBuilder.addHeader("Authorization", "Bearer " + token);
}
return chain.proceed(requestBuilder.build());
}
}
And here is my ApiClient class:
public class ApiClient {
public static final String BASE_URL = "some/url";
public static Retrofit retrofit = null;
public static Retrofit getApiClient(Context context) {
if (retrofit == null) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
AuthInterceptor authInterceptor = new AuthInterceptor(context);
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(authInterceptor)
.addInterceptor(logging)
.cookieJar(cookieJar)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okHttpClient)
.build();
}
return retrofit;
}
}
I feel these have been implemented correctly, but I am still unable to see the headers in my logs:
2023-01-26 13:35:53.361 7841-7924 okhttp.OkHttpClient com.example.releasesapp I --> POST http://.../loginuser.php
2023-01-26 13:35:53.361 7841-7924 okhttp.OkHttpClient com.example.releasesapp I Content-Type: application/json; charset=UTF-8
2023-01-26 13:35:53.361 7841-7924 okhttp.OkHttpClient com.example.releasesapp I Content-Length: 41
2023-01-26 13:35:53.361 7841-7924 okhttp.OkHttpClient com.example.releasesapp I {"email":"t#t.com","password":"test1234"}
2023-01-26 13:35:53.361 7841-7924 okhttp.OkHttpClient com.example.releasesapp I --> END POST (41-byte body)
2023-01-26 13:35:53.458 7841-7924 okhttp.OkHttpClient com.example.releasesapp I <-- 200 OK http://.../loginuser.php (96ms)
2023-01-26 13:35:53.458 7841-7924 okhttp.OkHttpClient com.example.releasesapp I Date: Thu, 26 Jan 2023 12:35:54 GMT
2023-01-26 13:35:53.458 7841-7924 okhttp.OkHttpClient com.example.releasesapp I Server: Apache/2.4.54 (Win64) OpenSSL/1.1.1p PHP/8.1.10
2023-01-26 13:35:53.458 7841-7924 okhttp.OkHttpClient com.example.releasesapp I X-Powered-By: PHP/8.1.10
2023-01-26 13:35:53.458 7841-7924 okhttp.OkHttpClient com.example.releasesapp I Expires: Thu, 19 Nov 1981 08:52:00 GMT
2023-01-26 13:35:53.458 7841-7924 okhttp.OkHttpClient com.example.releasesapp I Cache-Control: no-store, no-cache, must-revalidate
2023-01-26 13:35:53.458 7841-7924 okhttp.OkHttpClient com.example.releasesapp I Pragma: no-cache
2023-01-26 13:35:53.458 7841-7924 okhttp.OkHttpClient com.example.releasesapp I Set-Cookie: PHPSESSID=l08iqa7cs8tvt1bfnijkl1r7d8; path=/
2023-01-26 13:35:53.459 7841-7924 okhttp.OkHttpClient com.example.releasesapp I Content-Length: 194
2023-01-26 13:35:53.459 7841-7924 okhttp.OkHttpClient com.example.releasesapp I Keep-Alive: timeout=5, max=100
2023-01-26 13:35:53.459 7841-7924 okhttp.OkHttpClient com.example.releasesapp I Connection: Keep-Alive
2023-01-26 13:35:53.459 7841-7924 okhttp.OkHttpClient com.example.releasesapp I Content-Type: text/html; charset=UTF-8
2023-01-26 13:35:53.459 7841-7924 okhttp.OkHttpClient com.example.releasesapp I {"status_code":200,"auth_token":"TEMPTOKEN","user":{"id":"30","full_name":null,"username":"t","password_hash":"$2y","email":"t#t.com"}}
2023-01-26 13:35:53.459 7841-7924 okhttp.OkHttpClient com.example.releasesapp I <-- END HTTP (194-byte body)
Additionally, if I completely comment out my OkHttpClient (as well as the .client(okHttpClient) line), my log still shows okhttpclient. Is this normal?
Appreciate any help I can get with this.
try this I hope helpful you
private final OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS).addInterceptor(chain -> {
Request request = chain.request()
.newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Authorization",sessionManagement.getSessionToken() != null ? "Bearer " + sessionManagement.getSessionToken(): "")
.build();
return chain.proceed(request);
})
.addInterceptor(logging)
.build();
Interceptor that you set works in sequence that you set
It means if you set authInterceptor before logging then first authInterceptor executed and then logging will start to print so here you just need to change sequence
From
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(authInterceptor)
.addInterceptor(logging)
.cookieJar(cookieJar)
.build();
To
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(logging)
.addInterceptor(authInterceptor)
.cookieJar(cookieJar)
.build();
It looks like maybe my token was missing, because the original sequence seems to work fine now that I moved the code outside of the if statement (for now):
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(authInterceptor)
.addInterceptor(logging)
.cookieJar(cookieJar)
.build();
And my AuthInterceptor now looks like this:
requestBuilder.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Authorization", "Bearer " + token);
However, I was wondering why I wasn't getting a header with the json response. Is this supposed to also be handled by the Interceptor?
For the time being, I went ahead and added headers to my php code before passing back a response. I am not sure if this is how it's actually supposed to be done.
header("Accept: application/json");
header('Content-Type: application/json; charset=utf-8');
header("Authorization: Bearer " . $response['auth_token']);
echo json_encode($response);
exit;
I make similar request with postman and rest-assured with the same credentials and receiving different status codes. The only header which accept server is application/json. Data and url are similar. I tried to add headers from postman, but it failed. ResstAssured.auth() isn't fit for me. Maybe someone have solution or faced this problem.
Code example:
public Response userLogin() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("password", "pass");
jsonObject.put("account_name", "name");
jsonObject.put("email", "mail");
jsonObject.put("mfa_otp", 123456);
String url = "url";
return given()
.contentType(ContentType.JSON)
.body(jsonObject.toString())
.when()
.post(url)
.then()
.statusCode(200)
.extract()
.response();
}
Request:
Request method: POST
Request URI: url
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Content-Type=application/json; charset=UTF-8
Cookies: <none>
Multiparts: <none>
Body:
{
"password": "pass",
"account_name": "name",
"email": "mail"
}
Response:
HTTP/1.1 400 Bad Request
Date: Tue, 13 Apr 2021 19:27:16 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Server: nginx
X-Content-Type-Options: nosniff
X-Frame-Options: deny
Cache-Control: no-cache, no-store, must-revalidate
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: ETag, Link, X-Request-Id
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
X-Request-Id: 4e74caf3fa982d27cb827b5f7ebf6942
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
{
"status": "Bad Request",
"message": "Missing required parameter.",
"errors": [
{
"code": "required",
"field": "account_name"
}
]
}
Postman:
I figured out why It's happening every time, the Rest assured by default adding UTF-8 charset to content type.
Add this code to rest assured config method and you will be just fine, hope it will help to you.
private RestAssuredConfig decodeCharset = config().encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false));
This question already has an answer here:
CORS Error: “requests are only supported for protocol schemes: http…” etc
(1 answer)
Closed 3 years ago.
I am attempting to connect my angular app to my new Spring Boot 2 controller. I start everything up and I get:
Access to XMLHttpRequest at 'localhost:8093/restapi/setup' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Followed by:
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "localhost:8093/restapi/setup", ok: false, …}
So this is CORS, right? When I hit localhost:8093/restapi/setup from postman, I get a valid response, as you'd expect.
So I do some research and especially I find this: No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
I finally find this article here:
https://chariotsolutions.com/blog/post/angular-2-spring-boot-jwt-cors_part1/
And that leads me to the following code:
#Configuration
public class ManageConfiguration {
private static final Logger LOGGER = LogManager.getLogger(ManageConfiguration.class);
#Bean
public CorsFilter corsFilter() {
LOGGER.debug("Configuring CORS");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
So I think this is straightforward and now try again and I get:
Access to XMLHttpRequest at 'localhost:8093/restapi/setup' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Followed by:
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "localhost:8093/restapi/setup", ok: false, …}
So it doesn't appear to make any difference whatsoever.
Checked and it's running on the right port:
2019-02-27 14:23:21.261 INFO 9814 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8093 (http) with context path ''
Made sure it included my CORS bean:
2019-02-27 14:23:19.608 DEBUG 9814 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'corsFilter'
...
o.springframework.web.filter.CorsFilter : Filter 'corsFilter' configured for use
Per How can you debug a CORS request with cURL?, I did the following curl request to see my pre-flight stuff.
$ curl -H "Origin: http://example.com" --verbose http://localhost:8093/restapi/setup
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8093 (#0)
> GET /restapi/setup HTTP/1.1
> Host: localhost:8093
> User-Agent: curl/7.61.0
> Accept: */*
> Origin: http://example.com
>
< HTTP/1.1 200
< Vary: Origin
< Vary: Access-Control-Request-Method
< Vary: Access-Control-Request-Headers
< Access-Control-Allow-Origin: http://example.com
< Access-Control-Allow-Credentials: true
< 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-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Wed, 27 Feb 2019 21:38:28 GMT
<
* Connection #0 to host localhost left intact
{"issueType":["bug","epic","subTask","task","story"]}
Been scratching my head for a day about what to try next and can't come up with anything. Suggestions?
i think you're sending an ajax request without http:// protocol prefix in your request URL, try hitting http://localhost:8093/restapi/setup from ajax.
Add this WebSecurityConfigurerAdapter in your code
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
}
}
Also add the following WebMvcConfigurer
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class WebMvcConfigurerImpl implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
At last add this annotation on top of your rest controller class : #CrossOrigin.
#CrossOrigin
public class RestController {
// Your methods
}
If you have a filter, you can add the following attributes to the response, if you don't have, you can use this one.
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.OncePerRequestFilter;
#Service
public class JwtAuthenticationFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
response.setHeader("Access-Control-Expose-Headers", "Content-Length, Authorization");
filterChain.doFilter(request, response);
}
}
#Configuration
public class CorsConfig {
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*");
}
};
}
}
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
Please check the tutorial here https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
A Spring MVC controller needs to redirect the control flow of an app to a different url endpoint within the same app. But the current code is returning a blank page along with response headers that include the intended destination url as the forward header. When the contents of the forward header is pasted into the web browser, the intended endpoint is successfully called. What specific changes need to be made to the code below in order for the POST controller to successfully redirect the control flow to the intended destination endpoint instead of returning a blank page?
Here is the code for the Controller method:
#RequestMapping(method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<?> auth(FormData formData, HttpServletRequest req, HttpServletResponse resp) {
System.out.println("11111111111111 inside POST");
HttpHeaders responseHeaders = new HttpHeaders();
boolean passedTheTest = true;//ACTUAL LOGIC IS OMITTED HERE FOR SIMPLICITY
if (passedTheTest) {
//SOME OFF TOPIC LOGIC HERE IS OMITTED
CsrfToken csrf = (CsrfToken) req.getAttribute(CsrfToken.class.getName());
String updateCsrf = csrf.getToken();
responseHeaders.set("XSRF-TOKEN", updateCsrf);
if(resp.getHeaders("Cache-Control")!=null){responseHeaders.put("Cache-Control" , new ArrayList<String>(resp.getHeaders("Cache-Control")));}
if(resp.getHeader("Content-Language")!=null){responseHeaders.set("Content-Language" , resp.getHeader("Content-Language"));}
if(resp.getHeader("Content-Length")!=null){responseHeaders.set("Content-Length" , resp.getHeader("Content-Length"));}
if(resp.getHeader("Date")!=null){responseHeaders.set("Date" , resp.getHeader("Date"));}
if(resp.getHeader("Expires")!=null){responseHeaders.set("Expires" , resp.getHeader("Expires"));}
if(resp.getHeader("Pragma")!=null){responseHeaders.set("Pragma" , resp.getHeader("Pragma"));}
if(resp.getHeader("Server")!=null){responseHeaders.set("Server" , resp.getHeader("Server"));}
if(resp.getHeader("X-Application-Context")!=null){responseHeaders.set("X-Application-Context" , resp.getHeader("X-Application-Context"));}
if(resp.getHeader("X-Frame-Options")!=null){responseHeaders.set("X-Frame-Options" , resp.getHeader("X-Frame-Options"));}
if(resp.getHeader("X-XSS-Protection")!=null){responseHeaders.set("X-XSS-Protection" , resp.getHeader("X-XSS-Protection"));}
if(resp.getHeader("x-content-type-options")!=null){responseHeaders.set("x-content-type-options" , resp.getHeader("x-content-type-options"));}
if(req.getSession().getAttribute("forwardTo")!=null){
String redirectTo = getValidUriFromAnotherFunction();
try {
URI location = new URI(redirectTo);
responseHeaders.setLocation(location);
} catch (URISyntaxException e) {e.printStackTrace();}
ResponseEntity<Void> forwardResponseEntity = new ResponseEntity<Void>(responseHeaders, HttpStatus.CREATED);
return forwardResponseEntity;
}
};
return new ResponseEntity<String>("aDifferentViewTemplateName", responseHeaders, HttpStatus.CREATED);
}
The request headers in the browser's developer tools are:
Host: localhost:7777
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:7777/path/to/controller_method
Cookie: JSESSIONID=911B34457B69F7729091DD97A160AD79; JSESSIONID=95AA730306330CF15E3776C495807354; XSRF-TOKEN=04ae2a0c-3c58-4e85-88bd-3818bb10402a
Connection: keep-alive
The response headers for the same POST are:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate, no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Sun, 29 May 2016 21:48:24 GMT
Expires: 0, 0
Location: http://localhost:7777/path/to/forward_destination?long_querystring
Pragma: no-cache, no-cache
Server: Apache-Coyote/1.1
X-Application-Context: application:7777, application:7777
X-Content-Type-Options: nosniff, nosniff
X-Frame-Options: DENY, DENY
X-XSS-Protection: 1; mode=block, 1; mode=block
XSRF-TOKEN: 04ae2a0c-3c58-4e85-88bd-3818bb10402a
The Spring Boot debug log for the same POST includes three sections, which have been separated as follows for improved readability:
Section of debug log that shows the SYSO inside the controller:
11111111111111 inside POST
redirectTo is: http://localhost:7777/path/to/forward_destination?long_querystring
Section of debug log AFTER the controller (most important?):
2016-05-29 14:48:24.489 DEBUG 5533 --- [io-7777-exec-10] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2016-05-29 14:48:24.489 DEBUG 5533 --- [io-7777-exec-10] w.c.HttpSessionSecurityContextRepository : SecurityContext 'org.springframework.security.core.context.SecurityContextImpl#42259e42: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#42259e42: Principal: org.springframework.security.core.userdetails.User#40fecce: Username: SomeUser; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ONE,ROLE_TWO; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#fffe3f86: RemoteIpAddress: 127.0.0.1; SessionId: 02A95844E8A829868542290D471503F5; Granted Authorities: ROLE_ONE, ROLE_TWO, ROLE_THREE' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade#64307ead
2016-05-29 14:48:24.489 DEBUG 5533 --- [io-7777-exec-10] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Instead of returning the 201 Created status code you should return a 3XX status code to ask the user agent to load a different web page. Otherwise the Location header has no "special" meaning.
So for example you can write:
ResponseEntity<Void> forwardResponseEntity = new ResponseEntity<Void>(responseHeaders, HttpStatus.MOVED_PERMANENTLY);
Trying to download a file am getting an error, i couldn't able to download the file from Drive.
Here is the code i used
private static InputStream downloadFile(String token, File file) {
Drive service = getDriveService(getCredential(token));
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
and i'm getting this error
GET /a/thotz.net/uc?id=xxxxx&export=download HTTP/1.1
Host: docs.google.com
Content-length: 0
Authorization: OAuth ya29.AHES6ZTruwaMm_SHZAb9LFMCbxiJ85vaDccbil-h4enw
HTTP/1.1 401 Unauthorized
Content-length: 147
X-xss-protection: 1; mode=block
X-content-type-options: nosniff
X-google-cache-control: remote-fetch
-content-encoding: gzip
Server: GSE
Reason: Unauthorized
Via: HTTP/1.1 GWA
X-chromium-appcache-fallback-override: disallow-fallback
Cache-control: private, max-age=0
Date: Thu, 25 Apr 2013 19:54:12 GMT
X-frame-options: SAMEORIGIN
Content-type: text/html; charset=UTF-8
Expires: Thu, 25 Apr 2013 19:54:12 GMT
<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
i test the token in other request and is it work, so don't know why when i try to download a file show a 401 error.
I had similar problem using PHP library - turns out you need to make your request with authentication - 401 error means you are not authenticated.