Java:HttpServer提供轻量级http服务
【摘要】 JDK >= 6
package com.demo.desktop;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io....
JDK >= 6
package com.demo.desktop;
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;
/**
* 根据Java提供的API实现Http服务器
*/
public class MyHttpServer { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // 创建HttpServer服务器 HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 10); //将 / 请求交给MyHandler处理器处理 httpServer.createContext("/", new MyHandler()); httpServer.start(); }
}
class MyHandler implements HttpHandler { public void handle(HttpExchange httpExchange) throws IOException { String content = "hello"; //设置响应头属性及响应信息的长度 httpExchange.sendResponseHeaders(200, content.length()); //获得输出流 OutputStream os = httpExchange.getResponseBody(); os.write(content.getBytes()); os.close(); }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
请求:
GET http://localhost:8080/
返回:
hello
- 1
- 2
- 3
- 4
- 5
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/112768505
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)