java 如何在 REST API 中获取请求的客户端主机名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49043515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 10:15:00  来源:igfitidea点击:

How to get client Host name of request in REST API

javarestspring-mvcrequest-headers

提问by Megala Perumal

Currently I am working with Rest API(Spring MVC). UI Part is developed in Angular JS. this project will integrate any of the domain.

目前我正在使用 Rest API(Spring MVC)。UI 部分是用 Angular JS 开发的。该项目将集成任何域。

For example : www.xyz.comcontaining my register button www.abc.comalso may contain my register button.

例如:www.xyz.com包含我的注册按钮 www.abc.com也可能包含我的注册按钮。

When the request I received from user, I need to find out that, from which domain the request is coming?

当我从用户那里收到请求时,我需要找出请求来自哪个域?

Tried with the following:

尝试了以下内容:

@GET
@Path("/gethostname")
@Produces("application/json")
public void test(@Context HttpHeaders httpHeaders, @RequestBody JSONObject inputObj) {
    System.out.println("=========> "+httpHeaders.getHeaderString("host"));
}

But it return REST API(server) Host name. How can I get client host name?

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

回答by Pulkit

There are two ways for you to get hostname

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

By calling below code on server side, please note that this will come as null if url is directly entered in browser.

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

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

Check this imageenter image description here

检查这张图片在此处输入图片说明

Or you can provide below code to be added on client side and on server you can read the value of domainwhich will return hostname

或者您可以提供以下代码以添加到客户端和服务器上,您可以读取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>

回答by Bilal Raza

You can compare the Origin

你可以比较一下原产地

httpHeaders.getOrigin()

httpHeaders.getOrigin()

This returns the string which will tell you the origin of the request in your case http://www.yoursampleurl.com.

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

回答by Chids

Add HttpServletRequest request to your method definition and then use the Servlet API to get the Client remote address

将 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());
}