使用Spring Boot和Java 1.7通过Spring Rest从HTTP GET调用获取客户端的IP地址。
RestController:
@RestController
@RequestMapping("/api/v1")
public class IpFinderController {
private HttpHeaders headers;
private static final String[] IP_HEADER_CANDIDATES = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA", "REMOTE_ADDR"
};
public IpFinderController() {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
}
@RequestMapping(value = "/ipAddress", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<Object> getIpAddress(HttpServletRequest request)
throws IOException {
String remoteAddress = "";
if (request != null) {
remoteAddress = getClientIpAddress(request);
System.out.println("IP Address: " + remoteAddress);
}
return new ResponseEntity<Object>(remoteAddress, headers, HttpStatus.OK);
}
public static String getClientIpAddress(HttpServletRequest request) {
for (String header : IP_HEADER_CANDIDATES) {
String ip = request.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
}
return request.getRemoteAddr();
}
}
我是从stdout得到的:
IP Address: 0:0:0:0:0:0:0:1
但是我从REST Call(通过Swagger)得到了这个:
回应机构:
no content
回应代码:
0
响应标题:
{
"error": "no response from server"
}
从命令行使用curl时:
curl -i -X GET --header 'Accept: application/json' 'http://localhost:8080/ipservice/api/v1/ipAddress'
收到此输出:
curl: (3) Port number ended with ' '
0:0:0:0:0:0:0:1
问题(S):
为什么我得到0:0:0:0:0:0:0:1并且没有将其作为真实IP地址(是因为客户端在代理/路由器后面)?
为什么我在Swagger上通过“试一试”按钮运行时没有内容?
为什么从curl我有问题,为什么它不是JSON格式?
是否有任何第三方开源库可以帮助通过HTTP请求获取客户端的IP地址? (理想的客户端是命令行,Web浏览器和移动应用程序,无论是Android还是iOS)?