zoukankan      html  css  js  c++  java
  • java1.6的httpServer。可直接获取和处理http请求

       介绍摘自网络:

       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. }  

    二、测试类

    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. }  

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

    应修改为:

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

  • 相关阅读:
    RabbitMQ和Kafka的区别
    如何在 Vim 中复制,剪切,粘贴
    python中的堆支持自定义的比较函数
    LLDP协议(笔记草稿)
    You may have an infinite update loop in a component render function,vue模板报错
    修改element ui样式,el-dialog__header样式,并且不影响全局
    js,小数字符串去除右边零显示
    egg-sequelize创建表
    Cyclic dependency found. Users is dependent of itself,mysql表循环依赖问题
    eggjs sequelize操作多个数据,表名不加s,不默认加创建和修改时间字段
  • 原文地址:https://www.cnblogs.com/sanhuan/p/4632701.html
Copyright © 2011-2022 走看看