1.编写代码
import java.io.IOException;
import java.io.InputStream;import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
/**
* JDK6提供了一个简单的Http Server API, 据此我们可以构建自己的嵌入式Http Server,
* 它支持Http和Https协议,提供了HTTP1.1的部分实现, 没有被实现的那部分可以通过扩展已有的Http Server API来实现,
* 程序员必须自己实现HttpHandler接口, HttpServer会调用HttpHandler实现类的回调方法来处理客户端请求,
* 在这里,我们把一个Http请求和它的响应称为一个交换,包装成HttpExchange类
* HttpServer负责将HttpExchange传给HttpHandler实现类的回调方法.
*
* @author liudd
*
*/
public class HttpServerDemo {
public static void main(String[] args) {
try {
HttpServer hs = HttpServer.create(new InetSocketAddress(8888), 0);//设置httpserver的端口号8888
hs.createContext("/china",new Myhandler());//用MyHandler类内处理到/china的请求
hs.setExecutor(null);//创建默认一个executor
hs.start();
} catch (IOException e) {
// TODO: handle exception
}
}
}
class Myhandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
// TODO Auto-generated method stub
InputStream iStream = t.getRequestBody();
String response = "<h3>Happy day!!</h3>";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
2,运行程序,然后.在浏览器输入http://localhost:8888/china