用socket调用webservice

        最近开发项目中用到了WebService,自身项目对外发布时使用WebService作为服务端,而与其他应用集成的时候又成了对方WebService的客户端。由于自身项目使用的是XFire发布的WebService项目,在与其他项目集成作为客户端的时候XFire问题却显得异常突出,使用开发的JAX又会出现不兼容的现象。

       经过查找资料发现,可以使用socket进行soap协议的发送,相关问题迎刃而解。

       代码如下:

package com.evan;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.URL;

public class GenRand {
	public static void testGenRand() throws Exception {

		URL url = new URL("http://127.0.0.1:8080/mytest/tservice?wsdl");
		Socket s = new Socket(url.getHost(), url.getPort());
		try {
			s.setSoTimeout(30000); // Timeout 30 seconds
			InputStream socketIn = s.getInputStream();
			String length = "8";
			String content = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:impl=\"http://evan.com/services/impl/\">"
					+ "<soapenv:Header/>"
					+ "<soapenv:Body>"
					+ "<impl:genRAND>"
					+ "<length>"
					+ length
					+ "</length>"
					+ "</impl:genRAND>"
					+ "</soapenv:Body>"
					+ "</soapenv:Envelope>\r\n";

			String requestString = "POST " + url.getPath() + " HTTP/1.1\r\n"
					+ "Host: " + url.getHost() + ":" + url.getPort() + "\r\n"
					+ "Content-Type: text/xml; charset=utf-8\r\n"
					+ "Connection: close\r\n" + "Content-Length: "
					+ content.getBytes().length + "\r\n"
					+ "SOAPAction: \042\042\r\n" + "\r\n" + content;

			OutputStream os = s.getOutputStream();

			PrintStream ps = new PrintStream(os, true, "UTF-8");
			ps.println(requestString);

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] buffer = new byte[4096];
			while (true) {
				int nRead = socketIn.read(buffer);
				if (nRead == -1) {
					break;
				}
				bos.write(buffer, 0, nRead);
			}
			byte[] bs = bos.toByteArray();
			String result = new String(bs);
			String realResult = result.replace("&lt;", "<");
			System.out.println(realResult.substring(
					realResult.indexOf("<res>") + 5, realResult
							.indexOf("</res>")));
			// System.out.println("bs size:" + bs.length);
			// System.out.println("结果为:" + new String(bs));

		} finally {
			if (s != null)
				s.close();
		}

	}

	public static void main(String args[]) {
		try {
			testGenRand();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

       代码中对于流的关闭没有处理,开发中应该在finally中将所有使用到的流关闭。

你可能感兴趣的:(webservice)