java 如何使用普通的java类访问Web服务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13583918/
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
How to access web service using an ordinary java class?
提问by Edward Sagayaraj
**My Web service class**
import javax.jws.WebMethod;
import javax.jws.WebService;
/**
* @author edward
*
*/
@WebService
public class HelloWeb {
@WebMethod
public String sayGreeting(String name) {
return "Greeting " + name + "....!";
}
}
My Server java class
我的服务器java类
import javax.xml.ws.Endpoint;
public class Server {
public static void main(String[] args) {
Endpoint.publish("http://localhost:9090/HelloWeb", new HelloWeb());
System.out.println("Hello Web service is ready");
}
}
Server is running properly, and i am able to access the service using url that returns WSDL code.But i want to access the server using unique URL in java.I have the following client java code.
服务器运行正常,我能够使用返回 WSDL 代码的 url 访问服务。但我想使用 java 中的唯一 URL 访问服务器。我有以下客户端 java 代码。
Client to access HelloWeb Service
客户端访问HelloWeb服务
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;
public class WebClient {
String wsdl = "http://172.21.1.65:9090/HelloWeb?wsdl";
String namespace = "http://helloweb.com";
String serviceName = "HelloWebService";
QName serviceQN = new QName(namespace, serviceName);
{
try{
ServiceFactory serviceFactory = ServiceFactory.newInstance();
Service service = serviceFactory.createService(new URL(wsdl), serviceQN);
}catch (Exception e) {
}
}
}
回答by Evgeniy Dorofeev
try this, note that I compiled and ran your server in "test" package, it's important. This is just a basic example to start with JAX-WS.
试试这个,注意我在“测试”包中编译并运行了你的服务器,这很重要。这只是开始使用 JAX-WS 的一个基本示例。
package test;
import java.net.URL;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class WebClient {
@WebService(name = "HelloWeb", targetNamespace = "http://test/")
public interface HelloWeb {
@WebMethod
String sayGreeting(String name);
}
public static void main(String[] args) throws Exception {
Service serv = Service.create(new URL(
"http://localhost:9090/HelloWeb?wsdl"),
new QName("http://test/", "HelloWebService"));
HelloWeb p = serv.getPort(HelloWeb.class);
System.out.println(p.sayGreeting("John"));
}
}