Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Quick Tip: Spring REST Utility for Current HTTP Request

DZone's Guide to

Quick Tip: Spring REST Utility for Current HTTP Request

· Integration Zone
Free Resource

Learn how API management supports better integration in Achieving Enterprise Agility with Microservices and API Management, brought to you in partnership with 3scale

Utility Method for Spring REST

 public static HttpServletRequest getCurrentRequest() {
     RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
     Assert.state(requestAttributes != null, "Could not find current request via RequestContextHolder");
     Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes);
     HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
     Assert.state(servletRequest != null, "Could not find current HttpServletRequest");
     return servletRequest;
 }

Sometimes it’s easier to get the underlying Servlet request to get some headers or variables.

 final String userIpAddress = getCurrentRequest().getRemoteAddr();
 final String userAgent = getCurrentRequest().getHeader("user-agent");

This is used in the simple REST service using HTTP Post verb @ the awesome CloudFoundry:

(Source)

Tool for Creating Your Test JSON.

Spring Boot Documentation

Unleash the power of your APIs with future-proof API management - Create your account and start your free trial today, brought to you in partnership with 3scale.

Topics:

Published at DZone with permission of Tim Spann, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}