被告知查找请求源是否为浏览器。我有“用户代理”属性。
我在Chrome,Firefox和IE上进行了搜索,发现以下字符串:
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36
当我从API或邮递员发起带有上述'User-Agent'的请求时,如何检测是API击中还是浏览器击中?
是否有完整的方法来检测请求是否仅来自Web浏览器? (不是来自API,Postman或任何向其添加伪造的User-Agent的来源)
在Springboot中,这是实现的方法:
import javax.servlet.http.HttpServletRequest;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public ResponseEntity getHeaders(HttpServletRequest request) {
try {
String userAgent=request.getHeader("User-Agent");
//PostMan will always add **Postman-Token** to all of its requests
String postmanToken=request.getHeader("Postman-Token");
log.info("user agent: "+userAgent);
if(postmanToken!=null && !postmanToken.equals("")){
log.info("Request coming from postman");
}
return new ResponseEntity<>(HttpStatus.OK);
}catch (Exception e) {
log.error(e.getMessage(), e);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
现在您在userAgent属性中具有值,执行所需的相关操作。