Three ways to implement HTTP server

Source: Internet
Author: User
Tags httpcontext

First, use the new package provided by Sun Company in JDK6 Com.sun.net.httpserver


JDK6 provides a simple HTTP server API, whereby we can build our own embedded HTTP server, which supports HTTP and HTTPS protocols, and provides a partial implementation of the HTTP1.1, which can be implemented by extending an existing HTTP Server API to implement, the programmer must implement the HttpHandler interface on its own, Httpserver will invoke the callback method of the HttpHandler implementation class to handle the client request, where we call an HTTP request and its response as an exchange, Packaged as a Httpexchange class, Httpserver is responsible for passing httpexchange to the HttpHandler implementation class's callback method.
Implementing HTTP Server


Implementing HTTP server is simpler, I don't have to explain it, just look at the code below to understand.
Implementing HTTPS Server


HTTPS is a security-targeted HTTP channel, which is simply a secure version of HTTP. The SSL layer is added under HTTP, and the security basis of HTTPS is SSL,SSL using certificates for authentication. Certificates must be created for clients and servers that need to use SSL to secure communication. The certificate used by JSSE is created with the Java Keytool that is published with J2SE. Use the following command to create an RSA certificate for the HTTP server.
prompt> Keytool-genkey-keystore serverkeys-keyalg Rsa-alias Qusay
This command produces a certificate referenced by the alias Qusay and saves it in a file named Serverkeys. When the certificate is generated, the tool prompts us to enter some information.

The following code demonstrates how to create your own HTTP server and HTTPS server:

Java codeImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.net.InetSocketAddress;ImportCom.sun.net.httpserver.HttpExchange;ImportCom.sun.net.httpserver.HttpHandler;ImportCom.sun.net.httpserver.HttpServer; PublicclassMyhttpserver { PublicStatic voidMain (string[] args) {Try{//Implement HTTP SERVER httpserver HS = Httpserver.create (NewInetsocketaddress (8888), 0)//Set Httpserver port to Hs.createcontext ("/hujun",NewMyHandler ())/////Request Hs.setexecutor with MyHandler class (NULL);             Creates a default executor Hs.start (); Implement HTTPS SERVER Httpsserver HSS = httpsserver.create (NewInetsocketaddress (443), 0);   Set HTTPS port this 443 KeyStore KS = keystore.getinstance ("JKS"); Establish a certificate library Ks.load (NewFileInputStream ("certificate name"), "password");  Load certificate Keymanagerfactory KMF = keymanagerfactory.getinstance ("SunX509");  Establish a Key management factory Kmf.init (KS, "password");  Initial factory Sslcontext Sslcontext = sslcontext.getinstance ("SSLv3"); Establish the certificate Entity Sslcontext.init (Kmf.getkeymanagers (),NULL,NULL); Initialize certificate Httpsconfigurator conf =NewHttpsconfigurator (Sslcontext);   Configure Hss.sethttpsconfigurator (conf) at HTTPS; In the HTTPS server load configuration hss.setexecutor (NULL); Creates a default executor Hss.createcontext ("/",NewMyHandler ());///Request Hss.start () in the MyHandler class; }Catch(Exception e)        {E.printstacktrace (); }   } }classMyHandlerImplementsHttpHandler { PublicvoidHandle (Httpexchange t)throwsIOException {InputStream is = T.getrequestbody ();        String response = "<font color= ' #ff0000 ' >come on baby</font>";        T.sendresponseheaders (Response.length ());        OutputStream OS = T.getresponsebody ();        Os.write (Response.getbytes ());      Os.close (); }    }

Ii. use of Jetty


Jetty is an open source servlet container that provides a running environment for java-based Web content, such as JSPs and servlet. Jetty is written in the Java language, and its APIs are published in the form of a set of jar packages. Developers can instantiate an jetty container as an object and quickly provide network and web connectivity for some standalone-run (stand-alone) Java applications.


Minimum package Required:
Commons-logging.jar
Javax.servlet.jar
Org.mortbay.jetty.jar
Org.mortbay.jmx.jar

Now look directly at the code, in embedded mode to start jetty, currently does not seem to support HTTPS

Java codeImportOrg.mortbay.http.HttpContext;ImportOrg.mortbay.http.HttpServer;ImportOrg.mortbay.http.SocketListener;ImportOrg.mortbay.http.handler.ResourceHandler; PublicclassJettysample { PublicStatic voidMain (string[] args)throwsException {//Create Jetty Httpserver object Httpserver Server =NewHttpserver (); Bind a listener to the Httpserver object on port 8080 to enable it to receive HTTP requests SocketListener Listener =NewSocketListener ();        Listener.setport (8080);              Server.addlistener (listener);        Create a HttpContext to handle HTTP requests. HttpContext context =New httpcontext ();   ///use Setcontextpath to map the context to (/web) URLs.     Context.setcontextpath ("/web");   //setresourcebase method to set the document directory to provide resources   & nbsp

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.