HttpService的应用

/*
2 * $HeadURL: https://svn.apache.org/repos/asf/httpcomponents/httpcore/tags/4.0.1/httpcore/src/examples/org/apache/http/examples/ElementalHttpServer.java $
3 * $Revision: 744516 $
4 * $Date: 2009-02-14 17:38:14 +0100 (Sat, 14 Feb 2009) $
5 *
6 * ====================================================================
7 * Licensed to the Apache Software Foundation (ASF) under one
8 * or more contributor license agreements. See the NOTICE file
9 * distributed with this work for additional information
10 * regarding copyright ownership. The ASF licenses this file
11 * to you under the Apache License, Version 2.0 (the
12 * "License"); you may not use this file except in compliance
13 * with the License. You may obtain a copy of the License at
14 *
15 * http://www.apache.org/licenses/LICENSE-2.0
16 *
17 * Unless required by applicable law or agreed to in writing,
18 * software distributed under the License is distributed on an
19 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
20 * KIND, either express or implied. See the License for the
21 * specific language governing permissions and limitations
22 * under the License.
23 * ====================================================================
24 *
25 * This software consists of voluntary contributions made by many
26 * individuals on behalf of the Apache Software Foundation. For more
27 * information on the Apache Software Foundation, please see
28 * .
29 *
30 */
31
32 package [url=http://4007qwer.iteye.com/docs/api/org/apache/http/examples/package-index.html]org.apache.http.examples[/url];
33
34 import [url=http://4007qwer.iteye.com/docs/api/java/io/File.html]java.io.File[/url];
35 import [url=http://4007qwer.iteye.com/docs/api/java/io/IOException.html]java.io.IOException[/url];
36 import [url=http://4007qwer.iteye.com/docs/api/java/io/InterruptedIOException.html]java.io.InterruptedIOException[/url];
37 import [url=http://4007qwer.iteye.com/docs/api/java/io/OutputStream.html]java.io.OutputStream[/url];
38 import [url=http://4007qwer.iteye.com/docs/api/java/io/OutputStreamWriter.html]java.io.OutputStreamWriter[/url];
39 import [url=http://4007qwer.iteye.com/docs/api/java/net/ServerSocket.html]java.net.ServerSocket[/url];
40 import [url=http://4007qwer.iteye.com/docs/api/java/net/Socket.html]java.net.Socket[/url];
41 import [url=http://4007qwer.iteye.com/docs/api/java/net/URLDecoder.html]java.net.URLDecoder[/url];
42 import [url=http://4007qwer.iteye.com/docs/api/java/util/Locale.html]java.util.Locale[/url];
43
44 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/ConnectionClosedException.html]org.apache.http.ConnectionClosedException[/url];
45 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/HttpEntity.html]org.apache.http.HttpEntity[/url];
46 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/HttpEntityEnclosingRequest.html]org.apache.http.HttpEntityEnclosingRequest[/url];
47 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/HttpException.html]org.apache.http.HttpException[/url];
48 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/HttpRequest.html]org.apache.http.HttpRequest[/url];
49 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/HttpResponse.html]org.apache.http.HttpResponse[/url];
50 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/HttpServerConnection.html]org.apache.http.HttpServerConnection[/url];
51 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/HttpStatus.html]org.apache.http.HttpStatus[/url];
52 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/MethodNotSupportedException.html]org.apache.http.MethodNotSupportedException[/url];
53 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/entity/ContentProducer.html]org.apache.http.entity.ContentProducer[/url];
54 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/entity/EntityTemplate.html]org.apache.http.entity.EntityTemplate[/url];
55 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/entity/FileEntity.html]org.apache.http.entity.FileEntity[/url];
56 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/impl/DefaultConnectionReuseStrategy.html]org.apache.http.impl.DefaultConnectionReuseStrategy[/url];
57 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/impl/DefaultHttpResponseFactory.html]org.apache.http.impl.DefaultHttpResponseFactory[/url];
58 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/impl/DefaultHttpServerConnection.html]org.apache.http.impl.DefaultHttpServerConnection[/url];
59 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/params/BasicHttpParams.html]org.apache.http.params.BasicHttpParams[/url];
60 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/params/CoreConnectionPNames.html]org.apache.http.params.CoreConnectionPNames[/url];
61 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/params/HttpParams.html]org.apache.http.params.HttpParams[/url];
62 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/params/CoreProtocolPNames.html]org.apache.http.params.CoreProtocolPNames[/url];
63 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/protocol/BasicHttpProcessor.html]org.apache.http.protocol.BasicHttpProcessor[/url];
64 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/protocol/HttpContext.html]org.apache.http.protocol.HttpContext[/url];
65 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/protocol/BasicHttpContext.html]org.apache.http.protocol.BasicHttpContext[/url];
66 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/protocol/HttpRequestHandler.html]org.apache.http.protocol.HttpRequestHandler[/url];
67 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/protocol/HttpRequestHandlerRegistry.html]org.apache.http.protocol.HttpRequestHandlerRegistry[/url];
68 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/protocol/HttpService.html]org.apache.http.protocol.HttpService[/url];
69 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/protocol/ResponseConnControl.html]org.apache.http.protocol.ResponseConnControl[/url];
70 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/protocol/ResponseContent.html]org.apache.http.protocol.ResponseContent[/url];
71 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/protocol/ResponseDate.html]org.apache.http.protocol.ResponseDate[/url];
72 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/protocol/ResponseServer.html]org.apache.http.protocol.ResponseServer[/url];
73 import [url=http://4007qwer.iteye.com/docs/api/org/apache/http/util/EntityUtils.html]org.apache.http.util.EntityUtils[/url];
74
75 /**
76 * Basic, yet fully functional and spec compliant, HTTP/1.1 file server.
77 *
78 * Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
79 * It is NOT intended to demonstrate the most efficient way of building an HTTP file server.
80 *
81 *
82 * @version $Revision: 744516 $
83 */
84 public class ElementalHttpServer {
85
86 public static void main(String[] args) throws Exception {
87 if (args.length 91 Thread t = new RequestListenerThread(8080, args[0]);
92 t.setDaemon(false);
93 t.start();
94 }
95
96 static class HttpFileHandler implements HttpRequestHandler {
97
98 private final String docRoot;
99
100 public HttpFileHandler(final String docRoot) {
101 super();
102 this.docRoot = docRoot;
103 }
104
105 public void handle(
106 final HttpRequest request,
107 final HttpResponse response,
108 final HttpContext context) throws HttpException, IOException {
109
110 String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
111 if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
112 throw new MethodNotSupportedException(method + " method not supported");
113 }
114 String target = request.getRequestLine().getUri();
115
116 if (request instanceof HttpEntityEnclosingRequest) {
117 HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
118 byte[] entityContent = EntityUtils.toByteArray(entity);
119 System.out.println("Incoming entity content (bytes): " + entityContent.length);
120 }
121
122 final File file = new File(this.docRoot, URLDecoder.decode(target));
123 if (!file.exists()) {
124
125 response.setStatusCode(HttpStatus.SC_NOT_FOUND);
126 EntityTemplate body = new EntityTemplate(new ContentProducer() {
127
128 public void writeTo(final OutputStream outstream) throws IOException {
129 OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
130 writer.write("");
131 writer.write("File ");
132 writer.write(file.getPath());
133 writer.write(" not found");
134 writer.write("");
135 writer.flush();
136 }
137
138 });
139 body.setContentType("text/html; charset=UTF-8");
140 response.setEntity(body);
141 System.out.println("File " + file.getPath() + " not found");
142
143 } else if (!file.canRead() || file.isDirectory()) {
144
145 response.setStatusCode(HttpStatus.SC_FORBIDDEN);
146 EntityTemplate body = new EntityTemplate(new ContentProducer() {
147
148 public void writeTo(final OutputStream outstream) throws IOException {
149 OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
150 writer.write("");
151 writer.write("Access denied");
152 writer.write("");
153 writer.flush();
154 }
155
156 });
157 body.setContentType("text/html; charset=UTF-8");
158 response.setEntity(body);
159 System.out.println("Cannot read file " + file.getPath());
160
161 } else {
162
163 response.setStatusCode(HttpStatus.SC_OK);
164 FileEntity body = new FileEntity(file, "text/html");
165 response.setEntity(body);
166 System.out.println("Serving file " + file.getPath());
167
168 }
169 }
170
171 }
172
173 static class RequestListenerThread extends Thread {
174
175 private final ServerSocket serversocket;
176 private final HttpParams params;
177 private final HttpService httpService;
178
179 public RequestListenerThread(int port, final String docroot) throws IOException {
180 this.serversocket = new ServerSocket(port);
181 this.params = new BasicHttpParams();
182 this.params
183 .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
184 .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
185 .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
186 .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
187 .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
188
189 // Set up the HTTP protocol processor
190 BasicHttpProcessor httpproc = new BasicHttpProcessor();
191 httpproc.addInterceptor(new ResponseDate());
192 httpproc.addInterceptor(new ResponseServer());
193 httpproc.addInterceptor(new ResponseContent());
194 httpproc.addInterceptor(new ResponseConnControl());
195
196 // Set up request handlers
197 HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
198 reqistry.register("*", new HttpFileHandler(docroot));
199
200 // Set up the HTTP service
201 this.httpService = new HttpService(
202 httpproc,
203 new DefaultConnectionReuseStrategy(),
204 new DefaultHttpResponseFactory());
205 this.httpService.setParams(this.params);
206 this.httpService.setHandlerResolver(reqistry);
207 }
208
209 public void run() {
210 System.out.println("Listening on port " + this.serversocket.getLocalPort());
211 while (!Thread.interrupted()) {
212 try {
213 // Set up HTTP connection
214 Socket socket = this.serversocket.accept();
215 DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
216 System.out.println("Incoming connection from " + socket.getInetAddress());
217 conn.bind(socket, this.params);
218
219 // Start worker thread
220 Thread t = new WorkerThread(this.httpService, conn);
221 t.setDaemon(true);
222 t.start();
223 } catch (InterruptedIOException ex) {
224 break;
225 } catch (IOException e) {
226 System.err.println("I/O error initialising connection thread: "
227 + e.getMessage());
228 break;
229 }
230 }
231 }
232 }
233
234 static class WorkerThread extends Thread {
235
236 private final HttpService httpservice;
237 private final HttpServerConnection conn;
238
239 public WorkerThread(
240 final HttpService httpservice,
241 final HttpServerConnection conn) {
242 super();
243 this.httpservice = httpservice;
244 this.conn = conn;
245 }
246
247 public void run() {
248 System.out.println("New connection thread");
249 HttpContext context = new BasicHttpContext(null);
250 try {
251 while (!Thread.interrupted() && this.conn.isOpen()) {
252 this.httpservice.handleRequest(this.conn, context);
253 }
254 } catch (ConnectionClosedException ex) {
255 System.err.println("Client closed connection");
256 } catch (IOException ex) {
257 System.err.println("I/O error: " + ex.getMessage());
258 } catch (HttpException ex) {
259 System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
260 } finally {
261 try {
262 this.conn.shutdown();
263 } catch (IOException ignore) {}
264 }
265 }
266
267 }
268
269 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值