我想在servlet中直接调用网上提供的webservice具体怎么写代码。网上搜方法根本搜不到啊。T_T 求大神解救。
------解决思路----------------------
如果是要指定的调用某个webservice,可以用cxf,axis2,xfire等webservice技术根据webservice的wsdl地址生成客户端代码,然后在用这些技术的调用方式去调用。
如果是要通用的调用任何webservice,可以用httpclient模拟请求,webservice的soap协议、restful协议等等都是http协议的子集,模拟http请求都是可以调用的。只是要自己拼请求的字符串。
另外推荐一个工具SoapUI,开发和调试webservice必备工具。
------解决思路----------------------
下面是模拟的调用webservice接口,代码是放在main函数里的,可以直接复制粘贴到servlet里使用
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodRetryHandler;
import org.apache.commons.httpclient.NoHttpResponseException;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class TestWebService {
public static void main(String[] args) throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Message id=\"test\"></Message>";//以xml形式传送数据
byte[] xmlByte=xml.getBytes();
String url = "http://127.0.0.1:80/login.do";//webservice接口
Map params=new HashMap();//跟在webservice接口后面的参数,不是必须的
params.put("UserName", "username");
params.put("Password", "password");
String contentType="text/xml; charset=UTF-8";//因为是以xml形式传送数据,所以是text/xml
//后面都是调用apache的commons-httpclient-3.1.jar里的类
//需要用的其它jar包有commons-codec-1.3.jar和commons-logging.jar
//在apache的官网都可以下载到
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod(url);
byte[] postData = xmlByte;
if (postData != null) {//不是必须的
post.setRequestEntity(new ByteArrayRequestEntity(postData, "UTF-8"));
}
if (params != null && !params.isEmpty()) {
for (Iterator it = params.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
post.addParameter((String) entry.getKey(), (String) entry.getValue());
}
}
post.setRequestHeader("Content-type", contentType);
HttpMethodRetryHandler myretryhandler = new HttpMethodRetryHandler() {
public boolean retryMethod(final HttpMethod method, final IOException exception, int executionCount) {
if (executionCount >= 5) {
return false;
}
if (exception instanceof NoHttpResponseException) {
return true;
}
if (!method.isRequestSent()) {
return true;
}
return false;
}
};
post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, myretryhandler);
int result;
try {
result = httpclient.executeMethod(post);
byte body[] = null;
System.out.println(result);
switch (result) {
case 200://成功
body = post.getResponseBody();//body是WebService返回的数据的字节数组形式
System.out.println("接收WebService返回的数据:\r\n");
System.out.println(post.getResponseBodyAsString());
break;
default://其他情况,比如404、500等等
break;
}
} catch (Exception e) {
throw e;
} finally {
post.releaseConnection();
}
}
}
下面是模拟的一个简单的http服务器提供webservice服务,监听了80端口
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.net.*;
import java.util.concurrent.*;
public class SimpleHttpServer {
private int port = 80;
private ServerSocketChannel serverSocketChannel = null;
private ExecutorService executorService;
private static final int POOL_MULTIPLE = 4;
public SimpleHttpServer() throws IOException {
executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_MULTIPLE);
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().setReuseAddress(true);
serverSocketChannel.socket().bind(new InetSocketAddress(port));
System.out.println("服务器启动");
}
public void service() {
while (true) {
SocketChannel socketChannel = null;
try {
socketChannel = serverSocketChannel.accept();
executorService.execute(new Handler(socketChannel));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) throws IOException {
new SimpleHttpServer().service();
}
class Handler implements Runnable {
private SocketChannel socketChannel;
public Handler(SocketChannel socketChannel) {
this.socketChannel = socketChannel;
}
public void run() {
handle(socketChannel);
}
public void handle(SocketChannel socketChannel) {
try {
Socket socket = socketChannel.socket();
System.out.println("接收到客户连接,来自: " + socket.getInetAddress() + ":" + socket.getPort());
ByteBuffer buffer = ByteBuffer.allocate(1024);
socketChannel.read(buffer);
buffer.flip();
String request = decode(buffer);
System.out.print(request); // 打印HTTP请求
System.out.println("------------------打印HTTP请求结束-----------------------");
// 输出HTTP响应结果
StringBuffer sb = new StringBuffer("HTTP/1.1 200 OK\r\n");
sb.append("Content-Type:text/html\r\n\r\n");
socketChannel.write(encode(sb.toString()));// 输出响应头
FileInputStream in=null;
// 获得HTTP请求的第一行
String firstLineOfRequest = request.substring(0, request.indexOf("\r\n"));
if (firstLineOfRequest.indexOf("login.do") != -1) {
in = new FileInputStream("success.xml");
}
FileChannel fileChannel = in.getChannel();
fileChannel.transferTo(0, fileChannel.size(), socketChannel);
fileChannel.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (socketChannel != null) {
socketChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Charset charset = Charset.forName("GBK");
public String decode(ByteBuffer buffer) { // 解码
CharBuffer charBuffer = charset.decode(buffer);
return charBuffer.toString();
}
public ByteBuffer encode(String str) { // 编码
return charset.encode(str);
}
}
}
其中用的jar包有commons-httpclient-3.1.jar、commons-codec-1.3.jar和commons-logging.jar,在apache的官网都可以下载到
------解决思路----------------------
采用XFIRE,在doGet或doPost中这样写:
Client c = new Client(new URL(url));
Object result = c.invoke("getMehod", new Object[] {param1 , param2});
1、下载XFIRE依赖包:wsdl4j-1.6.2.jar、xfire-all-1.2.6.jar、xbean-spring-2.5.jar、spring-1.2.6.jar、jdom-1.0.jar、commons-logging-1.0.4.jar
2、把相关的JAR包依赖上去之后再使用Client对象new Client(new URL(url)).invoke("update", new Object[] {});
XFIRE官网:http://xfire.codehaus.org/
------解决思路----------------------
你先确定能在浏览器中能看到wsdl文件。剩下的就好做了。可以直接用Eclipse生成axis,或者直接用httpclient传递消息和接收消息。
------解决思路----------------------
还是一样,用eclipse/Myeclipse生成 一个webservice的wsdl客户端,然后你servlet想怎么调用怎么调用