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的官网都可以下载到

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/68205.html