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(); }
}
请求:
GET http://localhost:8080/
返回:
hello
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/112768505
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)