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. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStream;
  7. import java.net.InetSocketAddress;
  8. import com.sun.net.httpserver.HttpExchange;
  9. import com.sun.net.httpserver.HttpHandler;
  10. import com.sun.net.httpserver.HttpServer;
  11. import com.sun.net.httpserver.spi.HttpServerProvider;
  12. /**
  13. * @project SimpleHttpServer
  14. * @author sunnylocus
  15. * @vresion 1.0 2009-9-2
  16. * @description  自定义的http服务器
  17. */
  18. public class MyHttpServer {
  19. //启动服务,监听来自客户端的请求
  20. public static void httpserverService() throws IOException {
  21. HttpServerProvider provider = HttpServerProvider.provider();
  22. HttpServer httpserver =provider.createHttpServer(new InetSocketAddress(6666), 100);//监听端口6666,能同时接 受100个请求
  23. httpserver.createContext("/myApp", new MyHttpHandler());
  24. httpserver.setExecutor(null);
  25. httpserver.start();
  26. System.out.println("server started");
  27. }
  28. //Http请求处理类
  29. static class MyHttpHandler implements HttpHandler {
  30. public void handle(HttpExchange httpExchange) throws IOException {
  31. String responseMsg = "ok";   //响应信息
  32. InputStream in = httpExchange.getRequestBody(); //获得输入流
  33. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  34. String temp = null;
  35. while((temp = reader.readLine()) != null) {
  36. System.out.println("client request:"+temp);
  37. }
  38. httpExchange.sendResponseHeaders(200, responseMsg.length()); //设置响应头属性及响应信息的长度
  39. OutputStream out = httpExchange.getResponseBody();  //获得输出流
  40. out.write(responseMsg.getBytes());
  41. out.flush();
  42. httpExchange.close();
  43. }
  44. }
  45. public static void main(String[] args) throws IOException {
  46. httpserverService();
  47. }
  48. }

二、测试类

Java代码  

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

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

应修改为:

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

时间: 2024-09-10 10:05:39

java1.6的httpServer。可直接获取和处理http请求的相关文章

node的express框架,核心第三方模块body-parser 获取我们所有post请求传过来数据

- 安装 body-parser模块- npm install body-parser -S - 调用- let bodyParser=require('body-parser'); - 设置中间件- app.use(bodyParser.urlencoded({extended:true})); - 判断请求体格式是不是json格式,如果是的话会调用JSON.parse方法把请求体字符串转成对象 - app.use(bodyParser.json()); -上面两个只会有一个生效 - 获取po

小记:获取post和get请求。

1 package com.lixu.httpget_post; 2 import java.io.ByteArrayOutputStream; 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.UnsupportedEncodingException; 6 import java.util.ArrayList; 7 import java.util.List; 8 import org.ap

Unity 获取服务器时间 HTTP请求方式

在写每日签到的时候,我居然使用的是本地时间...被项目经理笑哭了...., 如果你在写单机游戏,没有游戏服务器,但又不想使用本地时间,就可以采用下面方法. 方法总结: 1. 使用HTTP请求获取服务器时间,不能实时获取服务器时间这样高频率的 2. 使用socket可以实时获取服务器时间 3. 使用C#自带API获取sql server 标准北京时间(=.=还没有找到这个API) 第HTTP方式: 代码: using UnityEngine; using System.Collections; u

js获取当前页面Get请求参数

废话不多说,直接上代码: //获取当前页面的请求参数并移除左边的? var currentSearchStr = window.location.search.replace("?",""); //将currentSearchStr分割到数组中 var currentSearchParamArr = currentSearchStr.split("&"); //将参数中的每一个值继续分割 var currentSearchParamDat

一般处理程序(ashx)获取不到POST请求的参数问题

写了一个一般处理程序来做接口,由于字段Content是文本,长度可能很长,鉴于这个原因,所以不能GET请求 所以问题来了,当我改成POST请求,自己使用HttpHelper类来写了一个Demo code var result = new HttpHelper().GetHtml(new HttpItem() { URL = "http://localhost:24885/Comment.ashx", Method = "POST", Postdata = "

NodeJS获取GET和POST请求

使用NodeJS获取GET请求,主要是通过使用NodeJS内置的querystring库处理req.url中的查询字符串来进行. 通过?将req.url分解成为一个包含path和query字符串的数组 通过querystring.parse()方法,对格式为key1=value1&key2=value2的查询字符串进行解析,并将其转换成为标准的JS对象 const http = require('http') const querystring = require('querystring')

Nginx 内置变量,细化规则,真实IP获取及限制连接请求

希望下周测试之后能用起来!!!感觉很有用的. http://www.bzfshop.net/article/176.html http://www.cr173.com/html/19761_1.html http://blog.pixelastic.com/2013/09/27/understanding-nginx-location-blocks-rewrite-rules/ 你 Google 不到的配置 很多时候,我们的网站不是简单的  普通用户IE浏览器  ——->  你的服务器  的结构

获取到ajax异步请求的数据的方法

// 通过GPS坐标取城市名 function getCityNameByLocation(lng, lat, callback) { // 参考:http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding $.ajax({ url: '//api.map.baidu.com/geocoder/v2/', type: 'GET', data: { ak: 'eNb809Xt5UBLLxCGKkmj6IOdEf

获取yii框架HTTP请求的方法

$request = Yii::$app->request; if ($request->isAjax) { /* 该请求是一个 AJAX 请求 */ } if ($request->isGet) { /* 请求方法是 GET */ } if ($request->isPost) { /* 请求方法是 POST */ } if ($request->isPut) { /* 请求方法是 PUT */ }