HttpServer的使用

http://docs.oracle.com/javase/8/docs/jre/api/net/httpserver/spec/overview-summary.html

1.Package com.sun.net.httpserver Description

Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.

Provides a simple high-level Http server API, which can be used to build embedded HTTP servers. Both "http" and "https" are supported. The API provides a partial implementation of RFC 2616 (HTTP 1.1) and RFC 2818 (HTTP over TLS). Any HTTP functionality not provided by this API can be implemented by application code using the API.

Programmers must implement the HttpHandler interface. This interface provides a callback which is invoked to handle incoming requests from clients. A HTTP request and its response is known as an exchange. HTTP exchanges are represented by the HttpExchange class. The HttpServer class is used to listen for incoming TCP connections and it dispatches requests on these connections to handlers which have been registered with the server.

A minimal Http server example is shown below:

   class MyHandler implements HttpHandler {
       public void handle(HttpExchange t) throws IOException {
           InputStream is = t.getRequestBody();
           read(is); // .. read the request body
           String response = "This is the response";
           t.sendResponseHeaders(200, response.length());
           OutputStream os = t.getResponseBody();
           os.write(response.getBytes());
           os.close();
       }
   }
   ...

   HttpServer server = HttpServer.create(new InetSocketAddress(8000));
   server.createContext("/applications/myapp", new MyHandler());
   server.setExecutor(null); // creates a default executor
   server.start();
   

The example above creates a simple HttpServer which uses the calling application thread to invoke the handle() method for incoming http requests directed to port 8000, and to the path /applications/myapp/.

The HttpExchange class encapsulates everything an application needs to process incoming requests and to generate appropriate responses.

Registering a handler with a HttpServer creates a HttpContext object and Filter objects can be added to the returned context. Filters are used to perform automatic pre- and post-processing of exchanges before they are passed to the exchange handler.

For sensitive information, a HttpsServer can be used to process "https" requests secured by the SSL or TLS protocols. A HttpsServer must be provided with a HttpsConfiguratorobject, which contains an initialized SSLContext. HttpsConfigurator can be used to configure the cipher suites and other SSL operating parameters. A simple example SSLContext could be created as follows:

   char[] passphrase = "passphrase".toCharArray();
   KeyStore ks = KeyStore.getInstance("JKS");
   ks.load(new FileInputStream("testkeys"), passphrase);

   KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
   kmf.init(ks, passphrase);

   TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
   tmf.init(ks);

   SSLContext ssl = SSLContext.getInstance("TLS");
   ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
   

In the example above, a keystore file called "testkeys", created with the keytool utility is used as a certificate store for client and server certificates. The following code shows how the SSLContext is then used in a HttpsConfigurator and how the SSLContext and HttpsConfigurator are linked to the HttpsServer.

    server.setHttpsConfigurator (new HttpsConfigurator(sslContext) {
        public void configure (HttpsParameters params) {

        // get the remote address if needed
        InetSocketAddress remote = params.getClientAddress();

        SSLContext c = getSSLContext();

        // get the default parameters
        SSLParameters sslparams = c.getDefaultSSLParameters();
        if (remote.equals (...) ) {
            // modify the default set for client x
        }

        params.setSSLParameters(sslparams);
        // statement above could throw IAE if any params invalid.
        // eg. if app has a UI and parameters supplied by a user.

        }
    });
   
Since:
1.6

2. Package com.sun.net.httpserver.spi Description

Provides a pluggable service provider interface, which allows the HTTP server implementation to be replaced with other implementations.

时间: 2024-10-29 19:06:08

HttpServer的使用的相关文章

Apache HTTPserver安装后报:无法启动,由于应用程序的并行配置不对-(已解决)

原创作品.出自 "深蓝的blog" 博客.欢迎转载,转载时请务必注明出处.否则有权追究版权法律责任. 深蓝的blog:http://blog.csdn.net/huangyanlong/article/details/46375453 安装Apache Http Server后报"应用程序无法启动,由于应用程序的并行配置不对"错误. 无法启动: 错误信息:应用程序无法启动,由于应用程序的并行配置不对.请參阅应用程序事件日志,或使用sxstrace.exe. 解决思路

restlet 2.3.5 org.restlet包导入eclipse出现的com.sun.net.httpserver类包找不到问题

准备过一遍restlet 2.3.5 JavaEE的源代码. 环境 eclipse3.7.2 和 jdk 7.0 将org.restlet 包加入到eclipse中,出现 com.sun.net.httpserver.*  包中的类无法找到. com.sun.net.httpserver是在jdk 6.0 就开始在jdk中提供的类. 解决方法: 1.修改位置和修改前的状态 2.修改 3.修改完后

node.js第十课(HTTPserver)

 概念:Node.js提供了http模块.当中封装了一个高效的HTTPserver和一个简单的HTTPclient. http.server是一个基于事件的HTTP服务器.内部用C++实现.接口由JavaScript封装. http.request则是一个HTTPclient工具.用户向server发送请求. 一.HTTPserver http.Server实现的,它提供了一套封装级别非常低的API,不过流控制和简单的解析,全部的高层功能都须要通过它的接口 前面解说的app.js案例 代码分

用http-server 创建node.js 静态服务器

今天做一本书上的例子,结果代码不能正常运行,查询了一下,是语法过时了,书其实是新买的,出版不久. 过时代码如下 var connect=require('connect'); connect.createServer( connect.static("../angularjs") ).listen(5000); 错误提示:connect.static不是一个方法 由于我的目的是练习angularjs,不是学习nodejs,所以不去深究,只要能建立一个简单的服务器就行 在网上搜到的方法是

web开发工具 http-server , grunt 使用

div#cpmenu {height:200px;float:left;} div#cpcontent {height:200px;width:150px;float:left;} 文章作者:松阳 原文链接:http://blog.csdn.net/fansongy/article/details/44121699 http-server 它是一个简单的服务部署,与Express相比,这货更轻了,它只是一个服务搭建工具,完全可以不安装到项目的目录中.安装使用: npm install -g ht

httpServer V1

1 package cn.edu.sss.httpServer; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.net.ServerSocket; 7 import java.net.Socket; 8 9 public class HttpServer1 { 10 11 public static void ma

Django之HttpServer服务器分析详解

大家知道,软件的正向工程,是从软件的需求获取开始,大概经历需求分析,概要分析,领域分析,设计分析,详细设计,代码实现,部署,实施这几个步骤,最终交付给用户使用.而在某些时候,比如某个软件产品是用PHP开发的,因为某些原因,我们想移植到JAVA平台去.或者某公司看到某个软件的市场前景很好,想COPY它的主要功能,然后经过加工润色后推出一个具有相同功能,更好用户体验或更多功能的软件.或者单纯的以研究软件的结构.设计思想为目的.基于这些需求,我们需要逆向工程.正向工程是一个从过程导出结果的步骤,而逆向

JAVA实现HTTPserver端

用java socket实现了一个简单的httpserver, 能够处理GET, POST,以及带一个附件的multipart类型的POST.尽管中途遇到了非常多问题, 只是通过在论坛和几个高手交流了一下,问题都攻克了.假设你认为程序有些地方看不明确,能够參看这个帖子:http://topic.csdn.net/u/20090625/22/59a5bfc8-a6b6-445d-9829-ea6d462a4fe6.html. 尽管解析http头不是非常规范,本来应该用原始的字节流, 我採用了一个折

tornado httpserver

这是一个非阻塞的,单线程的httpserver.这个类一般是不会被应用程序直接调用的,它一般是被上层的tornado.web.Application.listen方法调用,因为这个listen方法是这样定义的 def listen(self, port, address="", **kwargs): """Starts an HTTP server for this application on the given port. This is a conv

netty httpserver

netty也可以作为一个小巧的http服务器使用. 1 package com.ming.netty.http.httpserver; 2 3 import java.net.InetSocketAddress; 4 5 import io.netty.bootstrap.ServerBootstrap; 6 import io.netty.channel.ChannelFuture; 7 import io.netty.channel.ChannelInitializer; 8 import