JDK6新玩具---HttpServer的使用

   介绍摘自网络:

   JDK6提供了一个简单的Http Server API,据此我们可以构建自己的嵌入式Http Server,它支持Http和Https协议,提供了HTTP1.1的部分实现,没有被实现的那部分可以通过扩展已有的Http Server API来实现,程序员必须自己实现HttpHandler接口,HttpServer会调用HttpHandler实现类的回调方法来处理客户端请求,在这里,我们把一个Http请求和它的响应称为一个交换,包装成HttpExchange类,HttpServer负责将HttpExchange传给HttpHandler实现类的回调方法

 

   我想开发一个j2se的小程序,它能接受网页传来的参数,并对传来参数做些处理。我希望这个小程序即可能接受网页传过来的参数,也能接受OutputStream流传来参数,JDK6新特性能够实现。

一、提供http服务的类

package com.tdt.server.httpserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.spi.HttpServerProvider;

/**
 * @project SimpleHttpServer
 * @author sunnylocus
 * @vresion 1.0 2009-9-2
 * @description  自定义的http服务器
 */
public class MyHttpServer {
    //启动服务,监听来自客户端的请求
	public static void httpserverService() throws IOException {
		HttpServerProvider provider = HttpServerProvider.provider();
		HttpServer httpserver =provider.createHttpServer(new InetSocketAddress(6666), 100);//监听端口6666,能同时接 受100个请求
		httpserver.createContext("/myApp", new MyHttpHandler()); 
		httpserver.setExecutor(null);
		httpserver.start();
		System.out.println("server started");
	}
	//Http请求处理类
	static class MyHttpHandler implements HttpHandler {
		public void handle(HttpExchange httpExchange) throws IOException {
			String responseMsg = "ok";   //响应信息
			InputStream in = httpExchange.getRequestBody(); //获得输入流
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			String temp = null;
			while((temp = reader.readLine()) != null) {
				System.out.println("client request:"+temp);
			}
			httpExchange.sendResponseHeaders(200, responseMsg.length()); //设置响应头属性及响应信息的长度
			OutputStream out = httpExchange.getResponseBody();  //获得输出流
			out.write(responseMsg.getBytes());
			out.flush();
			httpExchange.close();                               
			
		}
	}
	public static void main(String[] args) throws IOException {
		httpserverService();
	}
}

 

二、测试类

package com.tdt.server.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @project SimpleHttpServer
 * @author sunnylocus
 * @vresion 1.0 2009-9-2
 * @description 测试类  
 */
public class Test {
	public static void main(String[] args) {
		ExecutorService exec = Executors.newCachedThreadPool();
		// 测试并发对MyHttpServer的影响
		for (int i = 0; i < 20; i++) {
			Runnable run = new Runnable() {
				public void run() {
					try {
						startWork();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			};
			exec.execute(run);
		}
		exec.shutdown();// 关闭线程池
	}

	public static void startWork() throws IOException {
		URL url = new URL("http://127.0.0.1:6666/myApp");
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		urlConn.setDoOutput(true);
		urlConn.setDoInput(true);
		urlConn.setRequestMethod("POST");
		// 测试内容包
		String teststr = "this is a test message";
		OutputStream out = urlConn.getOutputStream();
		out.write(teststr.getBytes());
		out.flush();
		while (urlConn.getContentLength() != -1) {
			if (urlConn.getResponseCode() == 200) {
				InputStream in = urlConn.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				String temp = "";
				while ((temp = reader.readLine()) != null) {
					System.err.println("server response:" + temp);// 打印收到的信息
				}
				reader.close();
				in.close();
				urlConn.disconnect();
			}
		}
	}
}

 

注意:经过我测试发现httpExchange.sendResponseHeaders(200, responseMsg.length())有bug,如果responseMsg里面包含中文的话,客户端不会收到任何信息,因为一个汉字用二个字节表示。

应修改为:

httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, responseMsg.getBytes().length);

你可能感兴趣的:(java,.net,J2SE,嵌入式,sun)