JDK1.6自帶的輕量級HTTP Server,無WEB容器暴露HTTP接口的解決方案

JDK6 提供了一個簡單的Http Server API,據此咱們能夠構建本身的嵌入式Http Server,它支持Http和Https協議,提供了HTTP1.1的部分實現,沒有被實現的那部分能夠經過擴展已有的Http Server API來實現,程序員必須本身實現HttpHandler接口,HttpServer會調用HttpHandler實現類的回調方法來處理客戶端請求,在 這裏,咱們把一個Http請求和它的響應稱爲一個交換,包裝成HttpExchange類,HttpServer負責將HttpExchange傳給 HttpHandler實現類的回調方法.html

import com.sun.net.httpserver.Headers;  
import com.sun.net.httpserver.HttpExchange;  
import com.sun.net.httpserver.HttpHandler;  
import com.sun.net.httpserver.HttpServer;  
  
import java.io.IOException;  
import java.io.OutputStream;  
import java.net.InetSocketAddress;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Set;  
import java.util.concurrent.Executors;  
  
//jdk自帶輕量級http server例子  http://127.0.0.1:8080/server  
public class HttpServerDemo {  
    public static void main(String[] args) throws IOException {  
        InetSocketAddress addr = new InetSocketAddress(8080);  
        HttpServer server = HttpServer.create(addr, 0);  
  
        server.createContext("/server", new MyHandler());  
        server.setExecutor(Executors.newCachedThreadPool());  
        server.start();  
        System.out.println("Server is listening on port 8080");  
    }  
}  
  
class MyHandler implements HttpHandler {  
    public void handle(HttpExchange exchange) throws IOException {  
        String requestMethod = exchange.getRequestMethod();  
        if (requestMethod.equalsIgnoreCase("GET")) {  
            Headers responseHeaders = exchange.getResponseHeaders();  
            responseHeaders.set("Content-Type", "text/plain");  
            // responseHeaders.set("Content-Type", "text/html; charset=utf-8");  
            exchange.sendResponseHeaders(200, 0);
           // exchange.sendResponseHeaders(200, response.getBytes("GBK").length);
  
            OutputStream responseBody = exchange.getResponseBody();  
            Headers requestHeaders = exchange.getRequestHeaders();  
            Set<String> keySet = requestHeaders.keySet();  
            Iterator<String> iter = keySet.iterator();  
            while (iter.hasNext()) {  
                String key = iter.next();  
                List values = requestHeaders.get(key);  
                String s = key + " = " + values.toString() + "\n";  
                responseBody.write(s.getBytes());  
            }  
            responseBody.write("jdk自帶輕量級http server例子".getBytes()); 
             //responseBody.write("jdk自帶輕量級http server例子".getBytes("GBK"));
            responseBody.close();  
        }  
    }  
}

 

回調方法裏不能經過spring的自動注入獲取bean的實例,所以若是想要調其餘接口,須要手動獲取該接口的實例java

final AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
retryBillService = (IRetryBillService) ctx.getBean("retryBillService");

注意,若是response中要輸出中文,頗有可能在瀏覽器種顯示亂碼,所以能夠以下操做:程序員

 exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes("GBK").length);spring

 responseBody.write(response.getBytes("GBK"));瀏覽器

經過設置編碼格式便可!!!app

若是想接受客戶端傳過來的GET參數,能夠經過以下代碼:

URI requestedUri = exchange.getRequestURI(); 

//好比客戶端請求鏈接爲http://10.17.2.205:8866/account?tradeDate=20170108
//那麼requestedUri.getRawQuery()獲得的值爲tradeDate=20170108,最後可解析該字符串獲得相關的參數

String query = requestedUri.getRawQuery();
相關文章
相關標籤/搜索