【问题标题】:How to get the client's host IP inside a JavaSE JAX-WS generated webservice Endpoint?如何在 JavaSE JAX-WS 生成的 Web 服务端点中获取客户端的主机 IP?
【发布时间】:2014-03-26 21:45:13
【问题描述】:

我正在 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);
   }
}

【问题讨论】:

标签: java web-services jax-ws endpoint


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多