`
4007qwer
  • 浏览: 9448 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
最近访客 更多访客>>
社区版块
存档分类
最新评论

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 org.apache.http.examples;
   33  
   34   import java.io.File;
   35   import java.io.IOException;
   36   import java.io.InterruptedIOException;
   37   import java.io.OutputStream;
   38   import java.io.OutputStreamWriter;
   39   import java.net.ServerSocket;
   40   import java.net.Socket;
   41   import java.net.URLDecoder;
   42   import java.util.Locale;
   43  
   44   import org.apache.http.ConnectionClosedException;
   45   import org.apache.http.HttpEntity;
   46   import org.apache.http.HttpEntityEnclosingRequest;
   47   import org.apache.http.HttpException;
   48   import org.apache.http.HttpRequest;
   49   import org.apache.http.HttpResponse;
   50   import org.apache.http.HttpServerConnection;
   51   import org.apache.http.HttpStatus;
   52   import org.apache.http.MethodNotSupportedException;
   53   import org.apache.http.entity.ContentProducer;
   54   import org.apache.http.entity.EntityTemplate;
   55   import org.apache.http.entity.FileEntity;
   56   import org.apache.http.impl.DefaultConnectionReuseStrategy;
   57   import org.apache.http.impl.DefaultHttpResponseFactory;
   58   import org.apache.http.impl.DefaultHttpServerConnection;
   59   import org.apache.http.params.BasicHttpParams;
   60   import org.apache.http.params.CoreConnectionPNames;
   61   import org.apache.http.params.HttpParams;
   62   import org.apache.http.params.CoreProtocolPNames;
   63   import org.apache.http.protocol.BasicHttpProcessor;
   64   import org.apache.http.protocol.HttpContext;
   65   import org.apache.http.protocol.BasicHttpContext;
   66   import org.apache.http.protocol.HttpRequestHandler;
   67   import org.apache.http.protocol.HttpRequestHandlerRegistry;
   68   import org.apache.http.protocol.HttpService;
   69   import org.apache.http.protocol.ResponseConnControl;
   70   import org.apache.http.protocol.ResponseContent;
   71   import org.apache.http.protocol.ResponseDate;
   72   import org.apache.http.protocol.ResponseServer;
   73   import org.apache.http.util.EntityUtils;
   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   }
分享到:
评论

相关推荐

    Flex+HTTPService 例子

    7. **HTTPServiceTest**:根据压缩包中的文件名,我们可以推测这个例子可能包含了一个简单的HTTPService测试应用。解压后,查看源代码能更深入地理解如何在实际项目中应用这些概念。 这个例子对于初学者来说非常...

    flex4 httpservice 例子

    在描述中提到的“提取XML数据”,指的是使用`HTTPService`从服务器获取XML格式的响应,并解析这些数据以供应用使用。 下面我们将详细介绍如何使用Flex4的`HTTPService`来提取XML数据: 1. **创建HTTPService实例**...

    flex httpservice 和 java通信 获取 java端的返回值

    Flex与Java之间的通信是Web应用程序开发中的常见需求,特别是在构建富客户端应用时。本文将详细介绍如何使用Flex的HTTPService组件与Java服务进行交互,并获取Java端的返回值。首先,让我们了解一下Flex和Java通信的...

    Flex4.0 如何通过 HttpService和WebService与服务器进行通信

    在Flex 4.0开发中,与服务器进行通信是实现应用程序功能的重要环节。HttpService和WebService是两种常用的方式,它们允许Flex客户端与基于HTTP或Web服务接口的后端系统进行数据交换。本篇文章将深入探讨如何利用Flex...

    Flex4_httpService

    这个项目展示了如何通过HTTPService组件在Flex应用中实现远程调用Java服务,以完成数据的交换和处理。Flex 4是Adobe AIR和Flash Player支持的ActionScript 3.0开发框架,它提供了一个强大的UI组件库和数据绑定机制,...

    java 中使用Flex的HttpService的详细配置

    在Java开发中,Flex HttpService是一个强大的工具,用于在Adobe Flex客户端与服务器之间进行数据通信。这个服务允许Flex应用程序通过HTTP协议发送请求到后端服务器,并接收响应数据。本篇文章将深入探讨如何在Java...

    将HttpService结果返回给控件

    在IT行业中,尤其是在Java或Android开发中,"将HttpService结果返回给控件"是一个常见的需求,涉及到网络请求、数据处理以及UI更新等关键环节。这里我们将深入探讨这个主题,并结合给定的"roomList.xml"文件名,推测...

    Flex HTTPService如何给后台传递参数 .doc

    在Flex开发中,HTTPService是用于与服务器进行异步HTTP通信的重要组件,它可以用来发送GET或POST请求到指定的Web服务接口。当我们需要向后台传递参数时,有多种方法可以实现,这里主要介绍两种常见的方法。 ### ...

    Flex+SpringMVC HttpService 发送XML数据

    本文将详细介绍如何使用Flex的HttpService组件向SpringMVC应用发送XML数据,并进行交互。 一、Flex中的HttpService组件 1. 创建HttpService:在Flex项目中,通过MXML或ActionScript可以创建HttpService实例。设置...

    HttpService_pb12.5

    - 示例代码(.pdi或.pwz):展示如何在PowerBuilder应用中使用`HttpService_pb12.5`的示例工程或窗口。 - 文档(.txt或.html):可能包含了使用该组件的指南、API参考或注意事项。 - 资源文件(如证书或配置文件):...

    flex httpservice实例

    在提供的代码片段中,我们看到一个简单的Flex应用程序示例,该应用使用了HTTPService组件来与后端服务进行交互。下面是对关键部分的详细分析: #### XML定义部分 ```xml ()"/> <mx:HTTPService id=...

    flex 解析xml文件 httpservice

    本篇文章将深入探讨如何使用Flex解析XML文件,并通过HTTPService来读取XML内容,以及如何根据需求过滤字符串并获取所需值。 首先,让我们了解Flex中的XML类。XML类是ActionScript 3.0中用于处理XML文档的主要工具,...

    FLEX 培训教材 主要讲到 HTTPSERVICE 和 WebService

    通过本教材,学习者将掌握如何创建Flex项目,理解Flex在Web工程中的应用,以及如何利用HTTPService和RemoteObject与服务器进行数据交互,从而实现富互联网应用的功能。同时,提供的参考资料和安装文件将有助于实际...

    FLEX _HTTPService的调用方法

    在Flex应用中,_HTTPService通常用于与后端服务器交互,以实现数据的获取或提交等功能。 ### 示例一:使用_HTTPService获取XML数据 **QueryDataSet.xml** 这是一个XML文件,包含了简单的商品信息列表。文件结构...

    flex与httpService通信(java)

    Flex是Adobe公司开发的一种富互联网应用(RIA)框架,它基于ActionScript编程语言和MXML标记语言,用于创建交互式的、动态的Web应用程序。在Flex中,`HTTPService`组件是用于与服务器进行数据交换的重要工具,特别是...

    flex与java通讯,URL,HTTPService,Socket

    Flex与Java之间的通信是开发跨平台应用程序时的关键技术,它允许客户端(通常为Flex应用程序)与服务器端(通常是Java应用程序)进行数据交换。本篇将深入探讨几种主要的通信方式:URLLoader,HTTPService和Socket。...

    flex实例HTTPService

    在Flex开发中,HTTPService是ActionScript 3.0中一个关键的组件,它允许开发者与...熟练掌握其用法,能有效提升你的Flex应用功能和用户体验。通过实际操作和实践,你可以进一步了解和掌握HTTPService的更多高级特性。

    Flex使用HttpService以键值对的形式发送请求,Java使用Servlet接收

    为了使这个通信工作,你需要在服务器上部署Servlet,并在Flex应用中正确配置`HttpService`的URL。在提供的压缩包文件中,可能包含了详细的文档和示例代码,可以帮助你更好地理解和实现这个过程。通过深入学习和实践...

    Flex的通信方式(三)——HTTPService_1

    在Flex应用中,HTTPService常用于获取或提交数据,例如从服务器检索JSON或XML格式的数据,或者提交表单数据到后端服务。 首先,我们需要了解HTTPService的基本使用。在MXML中,你可以创建一个HTTPService实例,并...

    Flex与Java低数据量通信息一:HTTPService

    总的来说,Flex与Java的低数据量通信主要依赖于HTTPService组件,它为跨平台的Flex应用提供了与Java后端进行数据交换的能力。理解这一通信机制对于开发富互联网应用至关重要,因为它涉及到前端与后端的交互,以及...

Global site tag (gtag.js) - Google Analytics