如何在JavaSE JAX-WS生成的Web服务端点中获取客户端的主机IP?

时间:2014-03-26 21:45:14

标签: java web-services jax-ws endpoint

我在JavaSE应用程序中启动WebService,我希望得到客户端的来电IP。 这可能吗?

我写了一个小测试用例:

import java.net.InetSocketAddress;
import java.util.concurrent.*;
import javax.jws.*;
import javax.xml.ws.Endpoint;
import com.sun.net.httpserver.*;

@WebService
public class TestWs {
   @WebMethod public String testMethod(String param) {
      String clientHostIp = ""; // how to obtain client's host ?
      return "hello "+ clientHostIp;
   }
   public static void main(String[] args) throws Exception {
      ExecutorService executorService = Executors.newFixedThreadPool(2);
      HttpServer thttpserver = HttpServer.create(new InetSocketAddress("0.0.0.0", 2000),8);
      final HttpServer httpserver = thttpserver;
      httpserver.setExecutor(executorService);
      httpserver.start();
      HttpContext ctx = httpserver.createContext("/TestWs");
      final Endpoint wsendpoint = Endpoint.create(new TestWs());
      wsendpoint.publish(ctx);
   }
}

1 个答案:

答案 0 :(得分:0)

This post帮我修复了我的问题,但它将我的代码绑定到内部sun API :(

import java.net.InetSocketAddress; 
import java.util.concurrent.*;
import javax.annotation.Resource;
import javax.jws.*;
import javax.xml.ws.*;
import com.sun.net.httpserver.*;
import com.sun.xml.internal.ws.developer.JAXWSProperties;

@WebService
public class TestWs {

   @Resource
   private WebServiceContext wsc;

   @WebMethod public String testMethod(String param) {
      HttpExchange exchange = (HttpExchange) wsc.getMessageContext().get(JAXWSProperties.HTTP_EXCHANGE);
      return "hello "+ exchange.getRemoteAddress().getHostString();
   }

   public static void main(String[] args) throws Exception {
      ExecutorService executorService = Executors.newFixedThreadPool(2);
      HttpServer thttpserver = HttpServer.create(new InetSocketAddress("0.0.0.0", 2000), 8);
      final HttpServer httpserver = thttpserver;
      httpserver.setExecutor(executorService);
      httpserver.start();
      HttpContext ctx = httpserver.createContext("/TestWs");
      final Endpoint wsendpoint = Endpoint.create(new TestWs());
      wsendpoint.publish(ctx);
   }
}