'Getting java.lang.IllegalStateException: No thread-bound request found when using Kafka Consumer to hit API
My requirement is to fetch cookie from the API requests and then pass on the same cookie to subsequent requests in order to maintain session using the same JsessionID.
For that I am trying to fetch cookie using HttpHeaders by Autowiring HttpServletRequests. If I hit an API using Controller I don't get any exception and I am able to fetch all the request attributes but if I run Kafka and API runs through Kafka Consumer, I am getting below exception:
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
@Autowired
HttpServletRequest req;
@Autowired
HttpServletResponse res;
public ResponseBean putData() {
String jsessionId = null;
String id = null;
// Creating Headers for request
String authValue = req.getHeader("authorization");
String headerCookie = req.getHeader("Cookie");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("authorization", authValue);
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.set(HttpHeaders.COOKIE, headerCookie);
HttpEntity httpEntity = new HttpEntity(httpHeaders);
ResponseEntity<String> responseEntity = restTemplate.exchange
("https://url", HttpMethod.POST, httpEntity, String.class);
jsessionId = responseEntity.getHeaders().getFirst("Set-Cookie");
if (jsessionId !=null && jsessionId.contains("JSESSION")) {
logger.info("New login session created");
id = jsessionId.substring(jsessionId.indexOf('=') + 1, jsessionId.indexOf(';'));
Cookie cookie = new Cookie("JSESSIONID", id);
res.addCookie(cookie);
}
}
PS- I am not using SpringSecurity.
Can anyone please help me in fixing the above issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
