如何在REST API中获取客户端主机名称

问题描述 投票:0回答:3

目前我正在使用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"));
}

但它返回REST API(服务器)主机名。如何获取客户端主机名?

java rest spring-mvc request-headers
3个回答
3
投票

有两种方法可以获取主机名

通过在服务器端调用下面的代码,请注意,如果直接在浏览器中输入url,这将为null。

String referrer = request.getHeader("referer");

检查这个图像enter image description here

或者您可以在客户端和服务器上提供以下代码,您可以读取将返回主机名的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>

1
投票

你可以比较Origin

httpHeaders.getOrigin()

这将返回字符串,该字符串将在您的案例http://www.yoursampleurl.com中告诉您请求的来源。


0
投票

将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());
}
© www.soinside.com 2019 - 2024. All rights reserved.