使用HttpCore(HttpComponents)在android上构建webService

来源:互联网 发布:贪吃蛇 c语言 编辑:程序博客网 时间:2024/06/10 23:48

使用HttpCore可以非常简单的构建HttpServer,HttpCore可以处理Http协议层。

工程里需要引入httpcore.jar,客户端开发需要引入httpclient.jar,下载地址:http://hc.apache.org/downloads.cgi

服务器端代码如下(get请求返回“<xml><method>get</method><url>&uri</url></xml>", post请求返回“<xml><method>post</method><url>&uri</url></xml>"):


[java] view plain copy
 print?
  1. package com.mytest.http;  
  2.   
  3.   
  4. import java.io.File;  
  5. import java.io.IOException;  
  6. import java.io.InterruptedIOException;  
  7. import java.net.ServerSocket;  
  8. import java.net.Socket;  
  9. import java.net.URLDecoder;  
  10. import java.nio.charset.Charset;  
  11. import java.util.Locale;  
  12.   
  13.   
  14. import org.apache.http.ConnectionClosedException;  
  15. import org.apache.http.HttpEntity;  
  16. import org.apache.http.HttpEntityEnclosingRequest;  
  17. import org.apache.http.HttpException;  
  18. import org.apache.http.HttpRequest;  
  19. import org.apache.http.HttpResponse;  
  20. import org.apache.http.HttpResponseInterceptor;  
  21. import org.apache.http.HttpServerConnection;  
  22. import org.apache.http.HttpStatus;  
  23. import org.apache.http.MethodNotSupportedException;  
  24. import org.apache.http.entity.ContentType;  
  25. import org.apache.http.entity.FileEntity;  
  26. import org.apache.http.entity.StringEntity;  
  27. import org.apache.http.impl.DefaultConnectionReuseStrategy;  
  28. import org.apache.http.impl.DefaultHttpResponseFactory;  
  29. import org.apache.http.impl.DefaultHttpServerConnection;  
  30. import org.apache.http.params.BasicHttpParams;  
  31. import org.apache.http.params.CoreConnectionPNames;  
  32. import org.apache.http.params.CoreProtocolPNames;  
  33. import org.apache.http.params.HttpParams;  
  34. import org.apache.http.protocol.BasicHttpContext;  
  35. import org.apache.http.protocol.HttpContext;  
  36. import org.apache.http.protocol.HttpProcessor;  
  37. import org.apache.http.protocol.HttpRequestHandler;  
  38. import org.apache.http.protocol.HttpRequestHandlerRegistry;  
  39. import org.apache.http.protocol.HttpService;  
  40. import org.apache.http.protocol.ImmutableHttpProcessor;  
  41. import org.apache.http.protocol.ResponseConnControl;  
  42. import org.apache.http.protocol.ResponseContent;  
  43. import org.apache.http.protocol.ResponseDate;  
  44. import org.apache.http.protocol.ResponseServer;  
  45. import org.apache.http.util.EntityUtils;  
  46.   
  47.   
  48. /** 
  49.  * Basic, yet fully functional and spec compliant, HTTP/1.1 file server. 
  50.  * <p> 
  51.  * Please note the purpose of this application is demonstrate the usage of 
  52.  * HttpCore APIs. It is NOT intended to demonstrate the most efficient way of 
  53.  * building an HTTP file server. 
  54.  *  
  55.  *  
  56.  */  
  57. public class HttpServer {  
  58.   
  59.   
  60.     public static void main(String[] args) throws Exception {  
  61.   
  62.   
  63.         Thread t = new RequestListenerThread(8080);  
  64.         t.setDaemon(false);  
  65.         t.start();      //start the webservice server  
  66.     }  
  67.   
  68.   
  69.   
  70.   
  71.     static class WebServiceHandler implements HttpRequestHandler {  
  72.   
  73.   
  74.         public WebServiceHandler() {  
  75.             super();  
  76.         }  
  77.   
  78.   
  79.         public void handle(final HttpRequest request,  
  80.                 final HttpResponse response, final HttpContext context)  
  81.                 throws HttpException, IOException {           
  82.   
  83.   
  84.             String method = request.getRequestLine().getMethod()  
  85.                     .toUpperCase(Locale.ENGLISH);  
  86.             //get uri  
  87.             String target = request.getRequestLine().getUri();  
  88.             if (method.equals("GET") ) {  
  89.                 response.setStatusCode(HttpStatus.SC_OK);  
  90.                 StringEntity entity = new StringEntity("<xml><method>get</method><url>" + target + "</url></xml>");  
  91.                 response.setEntity(entity);  
  92.             }  
  93.             else if (method.equals("POST") )  
  94.             {  
  95.                 response.setStatusCode(HttpStatus.SC_OK);  
  96.                 StringEntity entity = new StringEntity("<xml><method>post</method><url>" + target + "</url></xml>");  
  97.                 response.setEntity(entity);  
  98.             }  
  99.             else  
  100.             {  
  101.                 throw new MethodNotSupportedException(method  
  102.                         + " method not supported");  
  103.             }  
  104.         }  
  105.   
  106.   
  107.     }  
  108.   
  109.   
  110.     static class RequestListenerThread extends Thread {  
  111.   
  112.   
  113.         private final ServerSocket serversocket;  
  114.         private final HttpParams params;  
  115.         private final HttpService httpService;  
  116.   
  117.   
  118.         public RequestListenerThread(int port)  
  119.                 throws IOException {  
  120.             //   
  121.             this.serversocket = new ServerSocket(port);  
  122.   
  123.   
  124.             // Set up the HTTP protocol processor  
  125.             HttpProcessor httpproc = new ImmutableHttpProcessor(  
  126.                     new HttpResponseInterceptor[] {  
  127.                             new ResponseDate(), new ResponseServer(),  
  128.                             new ResponseContent(), new ResponseConnControl() });  
  129.   
  130.   
  131.             this.params = new BasicHttpParams();  
  132.             this.params  
  133.                     .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)  
  134.                     .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,  
  135.                             8 * 1024)  
  136.                     .setBooleanParameter(  
  137.                             CoreConnectionPNames.STALE_CONNECTION_CHECK, false)  
  138.                     .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)  
  139.                     .setParameter(CoreProtocolPNames.ORIGIN_SERVER,  
  140.                             "HttpComponents/1.1");  
  141.   
  142.   
  143.             // Set up request handlers  
  144.             HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();  
  145.             reqistry.register("*"new WebServiceHandler());  //WebServiceHandler用来处理webservice请求。  
  146.   
  147.   
  148.             this.httpService = new HttpService(httpproc,  
  149.                     new DefaultConnectionReuseStrategy(),  
  150.                     new DefaultHttpResponseFactory());  
  151.             httpService.setParams(this.params);  
  152.             httpService.setHandlerResolver(reqistry);       //为http服务设置注册好的请求处理器。  
  153.   
  154.   
  155.         }  
  156.   
  157.   
  158.         @Override  
  159.         public void run() {  
  160.             System.out.println("Listening on port "  
  161.                     + this.serversocket.getLocalPort());  
  162.             System.out.println("Thread.interrupted = " + Thread.interrupted());   
  163.             while (!Thread.interrupted()) {  
  164.                 try {  
  165.                     // Set up HTTP connection  
  166.                     Socket socket = this.serversocket.accept();  
  167.                     DefaultHttpServerConnection conn = new DefaultHttpServerConnection();  
  168.                     System.out.println("Incoming connection from "  
  169.                             + socket.getInetAddress());  
  170.                     conn.bind(socket, this.params);  
  171.   
  172.   
  173.                     // Start worker thread  
  174.                     Thread t = new WorkerThread(this.httpService, conn);  
  175.                     t.setDaemon(true);  
  176.                     t.start();  
  177.                 } catch (InterruptedIOException ex) {  
  178.                     break;  
  179.                 } catch (IOException e) {  
  180.                     System.err  
  181.                             .println("I/O error initialising connection thread: "  
  182.                                     + e.getMessage());  
  183.                     break;  
  184.                 }  
  185.             }  
  186.         }  
  187.     }  
  188.   
  189.   
  190.     static class WorkerThread extends Thread {  
  191.   
  192.   
  193.         private final HttpService httpservice;  
  194.         private final HttpServerConnection conn;  
  195.   
  196.   
  197.         public WorkerThread(final HttpService httpservice,  
  198.                 final HttpServerConnection conn) {  
  199.             super();  
  200.             this.httpservice = httpservice;  
  201.             this.conn = conn;  
  202.         }  
  203.   
  204.   
  205.         @Override  
  206.         public void run() {  
  207.             System.out.println("New connection thread");  
  208.             HttpContext context = new BasicHttpContext(null);  
  209.             try {  
  210.                 while (!Thread.interrupted() && this.conn.isOpen()) {  
  211.                     this.httpservice.handleRequest(this.conn, context);  
  212.                 }  
  213.             } catch (ConnectionClosedException ex) {  
  214.                 System.err.println("Client closed connection");  
  215.             } catch (IOException ex) {  
  216.                 System.err.println("I/O error: " + ex.getMessage());  
  217.             } catch (HttpException ex) {  
  218.                 System.err.println("Unrecoverable HTTP protocol violation: "  
  219.                         + ex.getMessage());  
  220.             } finally {  
  221.                 try {  
  222.                     this.conn.shutdown();  
  223.                 } catch (IOException ignore) {  
  224.                 }  
  225.             }  
  226.         }  
  227.     }  
  228. }  

客户端代码如下(注意,在Android 3.0及其后版本中,此端代码不能在main主线程里工作,否则会报网络异常导致退出):

[java] view plain copy
 print?
  1. DefaultHttpClient client = new DefaultHttpClient();  
  2.   
  3. HttpGet httpGet = new HttpGet(”http://localhost:8080/“);  
  4. HttpResponse httpResponse = client.execute(httpGet);  
  5. if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  6.     response = EntityUtils.toString(httpResponse.getEntity());  
  7. }  
原创粉丝点击