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

使用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>"):

 

  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. publicclassHttpServer{
  58.  
  59.  
  60. publicstaticvoid main(String[] args)throwsException{
  61.  
  62.  
  63. Thread t =newRequestListenerThread(8080);
  64. t.setDaemon(false);
  65. t.start();//start the webservice server
  66. }
  67.  
  68.  
  69.  
  70.  
  71. staticclassWebServiceHandlerimplementsHttpRequestHandler{
  72.  
  73.  
  74. publicWebServiceHandler(){
  75. super();
  76. }
  77.  
  78.  
  79. publicvoid handle(finalHttpRequest request,
  80. finalHttpResponse response,finalHttpContext context)
  81. throwsHttpException,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 =newStringEntity("<xml><method>get</method><url>"+ target +"</url></xml>");
  91. response.setEntity(entity);
  92. }
  93. elseif(method.equals("POST"))
  94. {
  95. response.setStatusCode(HttpStatus.SC_OK);
  96. StringEntity entity =newStringEntity("<xml><method>post</method><url>"+ target +"</url></xml>");
  97. response.setEntity(entity);
  98. }
  99. else
  100. {
  101. thrownewMethodNotSupportedException(method
  102. +" method not supported");
  103. }
  104. }
  105.  
  106.  
  107. }
  108.  
  109.  
  110. staticclassRequestListenerThreadextendsThread{
  111.  
  112.  
  113. privatefinalServerSocket serversocket;
  114. privatefinalHttpParamsparams;
  115. privatefinalHttpService httpService;
  116.  
  117.  
  118. publicRequestListenerThread(int port)
  119. throwsIOException{
  120. //
  121. this.serversocket =newServerSocket(port);
  122.  
  123.  
  124. // Set up the HTTP protocol processor
  125. HttpProcessor httpproc =newImmutableHttpProcessor(
  126. newHttpResponseInterceptor[]{
  127. newResponseDate(),newResponseServer(),
  128. newResponseContent(),newResponseConnControl()});
  129.  
  130.  
  131. this.params=newBasicHttpParams();
  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 =newHttpRequestHandlerRegistry();
  145. reqistry.register("*",newWebServiceHandler());//WebServiceHandler用来处理webservice请求。
  146.  
  147.  
  148. this.httpService =newHttpService(httpproc,
  149. newDefaultConnectionReuseStrategy(),
  150. newDefaultHttpResponseFactory());
  151. httpService.setParams(this.params);
  152. httpService.setHandlerResolver(reqistry);//为http服务设置注册好的请求处理器。
  153.  
  154.  
  155. }
  156.  
  157.  
  158. @Override
  159. publicvoid 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 =newDefaultHttpServerConnection();
  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 =newWorkerThread(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. staticclassWorkerThreadextendsThread{
  191.  
  192.  
  193. privatefinalHttpService httpservice;
  194. privatefinalHttpServerConnection conn;
  195.  
  196.  
  197. publicWorkerThread(finalHttpService httpservice,
  198. finalHttpServerConnection conn){
  199. super();
  200. this.httpservice = httpservice;
  201. this.conn = conn;
  202. }
  203.  
  204.  
  205. @Override
  206. publicvoid run(){
  207. System.out.println("New connection thread");
  208. HttpContext context =newBasicHttpContext(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主线程里工作,否则会报网络异常导致退出):

 

 

  1. DefaultHttpClient client =newDefaultHttpClient();
  2.  
  3. HttpGet httpGet =newHttpGet(”http://localhost:8080/“);
  4. HttpResponse httpResponse = client.execute(httpGet);
  5. if(httpResponse.getStatusLine().getStatusCode()==200){
  6. response =EntityUtils.toString(httpResponse.getEntity());
  7. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值