![](/img/trans.png)
[英]How do I get the full request URL with host-name/ip of a rest call?
[英]How to get client Host name of request in REST API
目前,我正在使用Rest API(Spring MVC)。 UI Part是用Angular JS开发的。 该项目将集成任何领域。
例如:含有www.xyz.com我的登记按钮www.abc.com还可以含有我的注册按钮。
当我收到来自用户的请求时,我需要找出该请求来自哪个域?
尝试了以下内容:
@GET
@Path("/gethostname")
@Produces("application/json")
public void test(@Context HttpHeaders httpHeaders, @RequestBody JSONObject inputObj) {
System.out.println("=========> "+httpHeaders.getHeaderString("host"));
}
但是它返回REST API(服务器)主机名。 如何获得客户端主机名?
有两种获取主机名的方法
通过在服务器端调用以下代码,请注意,如果直接在浏览器中输入url,则它将为null。
String referrer = request.getHeader("referer");
或者,您可以提供以下要添加到客户端和服务器上的代码,您可以读取将返回主机名的domain
的值
<input type="button" value="Register" onClick="call()"/>
<script>
function call(){
var domain=window.location.hostname;
window.open('http://<your-hostname>/register?domain='+domain,'_self');
}
</script>
将HttpServletRequest请求添加到您的方法定义中,然后使用Servlet API获取客户端远程地址
@GET
@Path("/gethostname")
@Produces("application/json")
public void test(@Context HttpHeaders httpHeaders, @RequestBody JSONObject inputObj,, HttpServletRequest request) {
System.out.println("=========> "+request.getRemoteAddr());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.