JDK6新玩具---HttpServer的使用

2009-09-02

JDK6新玩具---HttpServer的使用

關鍵字: httpserver httpserverprovider

   介紹摘自網絡:

   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服務的類

Java代碼 複製代碼
  1. package com.tdt.server.httpserver;   
  2.   
  3. import java.io.BufferedReader;   
  4. import java.io.IOException;   
  5. import java.io.InputStream;   
  6. import java.io.InputStreamReader;   
  7. import java.io.OutputStream;   
  8. import java.net.InetSocketAddress;   
  9.   
  10. import com.sun.net.httpserver.HttpExchange;   
  11. import com.sun.net.httpserver.HttpHandler;   
  12. import com.sun.net.httpserver.HttpServer;   
  13. import com.sun.net.httpserver.spi.HttpServerProvider;   
  14.   
  15. /**  
  16.  * @project SimpleHttpServer  
  17.  * @author sunnylocus  
  18.  * @vresion 1.0 2009-9-2  
  19.  * @description  自定義的http服務器  
  20.  */  
  21. public class MyHttpServer {   
  22.     //啓動服務,監聽來自客戶端的請求   
  23.     public static void httpserverService() throws IOException {   
  24.         HttpServerProvider provider = HttpServerProvider.provider();   
  25.         HttpServer httpserver =provider.createHttpServer(new InetSocketAddress(6666), 100);//監聽端口6666,能同時接 受100個請求   
  26.         httpserver.createContext("/myApp"new MyHttpHandler());    
  27.         httpserver.setExecutor(null);   
  28.         httpserver.start();   
  29.         System.out.println("server started");   
  30.     }   
  31.     //Http請求處理類   
  32.     static class MyHttpHandler implements HttpHandler {   
  33.         public void handle(HttpExchange httpExchange) throws IOException {   
  34.             String responseMsg = "ok";   //響應信息   
  35.             InputStream in = httpExchange.getRequestBody(); //獲得輸入流   
  36.             BufferedReader reader = new BufferedReader(new InputStreamReader(in));   
  37.             String temp = null;   
  38.             while((temp = reader.readLine()) != null) {   
  39.                 System.out.println("client request:"+temp);   
  40.             }   
  41.             httpExchange.sendResponseHeaders(200, responseMsg.length()); //設置響應頭屬性及響應信息的長度   
  42.             OutputStream out = httpExchange.getResponseBody();  //獲得輸出流   
  43.             out.write(responseMsg.getBytes());   
  44.             out.flush();   
  45.             httpExchange.close();                                  
  46.                
  47.         }   
  48.     }   
  49.     public static void main(String[] args) throws IOException {   
  50.         httpserverService();   
  51.     }   
  52. }  
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();
	}
}

 

二、測試類

Java代碼 複製代碼
  1. package com.tdt.server.test;   
  2.   
  3. import java.io.BufferedReader;   
  4. import java.io.IOException;   
  5. import java.io.InputStream;   
  6. import java.io.InputStreamReader;   
  7. import java.io.OutputStream;   
  8. import java.net.HttpURLConnection;   
  9. import java.net.URL;   
  10. import java.util.concurrent.ExecutorService;   
  11. import java.util.concurrent.Executors;   
  12.   
  13. /**  
  14.  * @project SimpleHttpServer  
  15.  * @author sunnylocus  
  16.  * @vresion 1.0 2009-9-2  
  17.  * @description 測試類    
  18.  */  
  19. public class Test {   
  20.     public static void main(String[] args) {   
  21.         ExecutorService exec = Executors.newCachedThreadPool();   
  22.         // 測試併發對MyHttpServer的影響   
  23.         for (int i = 0; i < 20; i++) {   
  24.             Runnable run = new Runnable() {   
  25.                 public void run() {   
  26.                     try {   
  27.                         startWork();   
  28.                     } catch (IOException e) {   
  29.                         e.printStackTrace();   
  30.                     }   
  31.                 }   
  32.             };   
  33.             exec.execute(run);   
  34.         }   
  35.         exec.shutdown();// 關閉線程池   
  36.     }   
  37.   
  38.     public static void startWork() throws IOException {   
  39.         URL url = new URL("http://127.0.0.1:6666/myApp");   
  40.         HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();   
  41.         urlConn.setDoOutput(true);   
  42.         urlConn.setDoInput(true);   
  43.         urlConn.setRequestMethod("POST");   
  44.         // 測試內容包   
  45.         String teststr = "this is a test message";   
  46.         OutputStream out = urlConn.getOutputStream();   
  47.         out.write(teststr.getBytes());   
  48.         out.flush();   
  49.         while (urlConn.getContentLength() != -1) {   
  50.             if (urlConn.getResponseCode() == 200) {   
  51.                 InputStream in = urlConn.getInputStream();   
  52.                 BufferedReader reader = new BufferedReader(new InputStreamReader(in));   
  53.                 String temp = "";   
  54.                 while ((temp = reader.readLine()) != null) {   
  55.                     System.err.println("server response:" + temp);// 打印收到的信息   
  56.                 }   
  57.                 reader.close();   
  58.                 in.close();   
  59.                 urlConn.disconnect();   
  60.             }   
  61.         }   
  62.     }   
  63. }  
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);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章