使用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>"):
- package com.mytest.http;
- import java.io.File;
- import java.io.IOException;
- import java.io.InterruptedIOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.net.URLDecoder;
- import java.nio.charset.Charset;
- import java.util.Locale;
- import org.apache.http.ConnectionClosedException;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpEntityEnclosingRequest;
- import org.apache.http.HttpException;
- import org.apache.http.HttpRequest;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpResponseInterceptor;
- import org.apache.http.HttpServerConnection;
- import org.apache.http.HttpStatus;
- import org.apache.http.MethodNotSupportedException;
- import org.apache.http.entity.ContentType;
- import org.apache.http.entity.FileEntity;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.DefaultConnectionReuseStrategy;
- import org.apache.http.impl.DefaultHttpResponseFactory;
- import org.apache.http.impl.DefaultHttpServerConnection;
- import org.apache.http.params.BasicHttpParams;
- import org.apache.http.params.CoreConnectionPNames;
- import org.apache.http.params.CoreProtocolPNames;
- import org.apache.http.params.HttpParams;
- import org.apache.http.protocol.BasicHttpContext;
- import org.apache.http.protocol.HttpContext;
- import org.apache.http.protocol.HttpProcessor;
- import org.apache.http.protocol.HttpRequestHandler;
- import org.apache.http.protocol.HttpRequestHandlerRegistry;
- import org.apache.http.protocol.HttpService;
- import org.apache.http.protocol.ImmutableHttpProcessor;
- import org.apache.http.protocol.ResponseConnControl;
- import org.apache.http.protocol.ResponseContent;
- import org.apache.http.protocol.ResponseDate;
- import org.apache.http.protocol.ResponseServer;
- import org.apache.http.util.EntityUtils;
- /**
- * Basic, yet fully functional and spec compliant, HTTP/1.1 file server.
- * <p>
- * Please note the purpose of this application is demonstrate the usage of
- * HttpCore APIs. It is NOT intended to demonstrate the most efficient way of
- * building an HTTP file server.
- *
- *
- */
- publicclassHttpServer{
- publicstaticvoid main(String[] args)throwsException{
- Thread t =newRequestListenerThread(8080);
- t.setDaemon(false);
- t.start();//start the webservice server
- }
- staticclassWebServiceHandlerimplementsHttpRequestHandler{
- publicWebServiceHandler(){
- super();
- }
- publicvoid handle(finalHttpRequest request,
- finalHttpResponse response,finalHttpContext context)
- throwsHttpException,IOException{
- String method = request.getRequestLine().getMethod()
- .toUpperCase(Locale.ENGLISH);
- //get uri
- String target = request.getRequestLine().getUri();
- if(method.equals("GET")){
- response.setStatusCode(HttpStatus.SC_OK);
- StringEntity entity =newStringEntity("<xml><method>get</method><url>"+ target +"</url></xml>");
- response.setEntity(entity);
- }
- elseif(method.equals("POST"))
- {
- response.setStatusCode(HttpStatus.SC_OK);
- StringEntity entity =newStringEntity("<xml><method>post</method><url>"+ target +"</url></xml>");
- response.setEntity(entity);
- }
- else
- {
- thrownewMethodNotSupportedException(method
- +" method not supported");
- }
- }
- }
- staticclassRequestListenerThreadextendsThread{
- privatefinalServerSocket serversocket;
- privatefinalHttpParamsparams;
- privatefinalHttpService httpService;
- publicRequestListenerThread(int port)
- throwsIOException{
- //
- this.serversocket =newServerSocket(port);
- // Set up the HTTP protocol processor
- HttpProcessor httpproc =newImmutableHttpProcessor(
- newHttpResponseInterceptor[]{
- newResponseDate(),newResponseServer(),
- newResponseContent(),newResponseConnControl()});
- this.params=newBasicHttpParams();
- this.params
- .setIntParameter(CoreConnectionPNames.SO_TIMEOUT,5000)
- .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
- 8*1024)
- .setBooleanParameter(
- CoreConnectionPNames.STALE_CONNECTION_CHECK,false)
- .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,true)
- .setParameter(CoreProtocolPNames.ORIGIN_SERVER,
- "HttpComponents/1.1");
- // Set up request handlers
- HttpRequestHandlerRegistry reqistry =newHttpRequestHandlerRegistry();
- reqistry.register("*",newWebServiceHandler());//WebServiceHandler用来处理webservice请求。
- this.httpService =newHttpService(httpproc,
- newDefaultConnectionReuseStrategy(),
- newDefaultHttpResponseFactory());
- httpService.setParams(this.params);
- httpService.setHandlerResolver(reqistry);//为http服务设置注册好的请求处理器。
- }
- @Override
- publicvoid run(){
- System.out.println("Listening on port "
- +this.serversocket.getLocalPort());
- System.out.println("Thread.interrupted = "+Thread.interrupted());
- while(!Thread.interrupted()){
- try{
- // Set up HTTP connection
- Socket socket =this.serversocket.accept();
- DefaultHttpServerConnection conn =newDefaultHttpServerConnection();
- System.out.println("Incoming connection from "
- + socket.getInetAddress());
- conn.bind(socket,this.params);
- // Start worker thread
- Thread t =newWorkerThread(this.httpService, conn);
- t.setDaemon(true);
- t.start();
- }catch(InterruptedIOException ex){
- break;
- }catch(IOException e){
- System.err
- .println("I/O error initialising connection thread: "
- + e.getMessage());
- break;
- }
- }
- }
- }
- staticclassWorkerThreadextendsThread{
- privatefinalHttpService httpservice;
- privatefinalHttpServerConnection conn;
- publicWorkerThread(finalHttpService httpservice,
- finalHttpServerConnection conn){
- super();
- this.httpservice = httpservice;
- this.conn = conn;
- }
- @Override
- publicvoid run(){
- System.out.println("New connection thread");
- HttpContext context =newBasicHttpContext(null);
- try{
- while(!Thread.interrupted()&&this.conn.isOpen()){
- this.httpservice.handleRequest(this.conn, context);
- }
- }catch(ConnectionClosedException ex){
- System.err.println("Client closed connection");
- }catch(IOException ex){
- System.err.println("I/O error: "+ ex.getMessage());
- }catch(HttpException ex){
- System.err.println("Unrecoverable HTTP protocol violation: "
- + ex.getMessage());
- }finally{
- try{
- this.conn.shutdown();
- }catch(IOException ignore){
- }
- }
- }
- }
- }
客户端代码如下(注意,在android 3.0及其后版本中,此端代码不能在main主线程里工作,否则会报网络异常导致退出):
- DefaultHttpClient client =newDefaultHttpClient();
- HttpGet httpGet =newHttpGet(”http://localhost:8080/“);
- HttpResponse httpResponse = client.execute(httpGet);
- if(httpResponse.getStatusLine().getStatusCode()==200){
- response =EntityUtils.toString(httpResponse.getEntity());
- }