如何使用普通的java类访问Web服务? [英] How to access web service using an ordinary java class?
本文介绍了如何使用普通的java类访问Web服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
**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 + "....!";
}
}
我的服务器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");
}
}
服务器运行正常,我可以访问使用返回WSDL代码的url的服务。但我想在java中使用唯一的URL访问服务器。我有以下客户端java代码。
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.
客户端到访问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) {
}
}
}
推荐答案
试试这个,请注意我在test包中编译并运行了你的服务器,这很重要。这只是从JAX-WS开始的一个基本示例。
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.
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"));
}
}
这篇关于如何使用普通的java类访问Web服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文