- 工具类
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
public class HeadUtil {
public static HttpServletRequest getRequest() {
return Optional.ofNullable(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())).orElseThrow(() -> new RuntimeException("未获取到当前请求信息")).getRequest();
}
public static String getHeadKey(String key) {
String value = HeadUtil.getRequest().getHeader(key);
if (StringUtils.isEmpty(value)) {
throw new RuntimeException("无法获取"+key);
}
return value;
}
}
- demo
@RestController
@RequestMapping("head")
public class HeadController {
@GetMapping
public void test(){
String headKey = HeadUtil.getHeadKey("test-test");
System.out.println(headKey);
}
}
