如何在 REST 中获取请求的客户端主机名 API
How to get client Host name of request in REST API
目前我正在使用 Rest API(Spring MVC)。 UI 部分是用 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"));
}
但它 return REST API(服务器)主机名。如何获取客户端主机名?
将 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());
}
你可以比较原点
httpHeaders.getOrigin()
此 returns 字符串将告诉您请求的来源
http://www.yoursampleurl.com.
您可以通过两种方式获取主机名
通过在服务器端调用以下代码,请注意,如果直接在浏览器中输入 url,这将返回 null。
String referrer = request.getHeader("referer");
检查这张图片
或者您可以提供以下代码添加到客户端,在服务器端您可以读取 domain
的值,这将 return hostname
<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>
目前我正在使用 Rest API(Spring MVC)。 UI 部分是用 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"));
}
但它 return REST API(服务器)主机名。如何获取客户端主机名?
将 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());
}
你可以比较原点
httpHeaders.getOrigin()
此 returns 字符串将告诉您请求的来源 http://www.yoursampleurl.com.
您可以通过两种方式获取主机名
通过在服务器端调用以下代码,请注意,如果直接在浏览器中输入 url,这将返回 null。
String referrer = request.getHeader("referer");
检查这张图片
或者您可以提供以下代码添加到客户端,在服务器端您可以读取 domain
的值,这将 return hostname
<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>