使用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>"):
- 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;
-
-
-
-
-
-
-
-
-
-
-
- public class HttpServer {
-
-
- public static void main(String[] args) throws Exception {
-
-
- Thread t = new RequestListenerThread(8080);
- t.setDaemon(false);
- t.start();
- }
-
-
-
-
- static class WebServiceHandler implements HttpRequestHandler {
-
-
- public WebServiceHandler() {
- super();
- }
-
-
- public void handle(final HttpRequest request,
- final HttpResponse response, final HttpContext context)
- throws HttpException, IOException {
-
-
- String method = request.getRequestLine().getMethod()
- .toUpperCase(Locale.ENGLISH);
-
- String target = request.getRequestLine().getUri();
- if (method.equals("GET") ) {
- response.setStatusCode(HttpStatus.SC_OK);
- StringEntity entity = new StringEntity("<xml><method>get</method><url>" + target + "</url></xml>");
- response.setEntity(entity);
- }
- else if (method.equals("POST") )
- {
- response.setStatusCode(HttpStatus.SC_OK);
- StringEntity entity = new StringEntity("<xml><method>post</method><url>" + target + "</url></xml>");
- response.setEntity(entity);
- }
- else
- {
- throw new MethodNotSupportedException(method
- + " method not supported");
- }
- }
-
-
- }
-
-
- static class RequestListenerThread extends Thread {
-
-
- private final ServerSocket serversocket;
- private final HttpParams params;
- private final HttpService httpService;
-
-
- public RequestListenerThread(int port)
- throws IOException {
-
- this.serversocket = new ServerSocket(port);
-
-
-
- HttpProcessor httpproc = new ImmutableHttpProcessor(
- new HttpResponseInterceptor[] {
- new ResponseDate(), new ResponseServer(),
- new ResponseContent(), new ResponseConnControl() });
-
-
- this.params = new BasicHttpParams();
- 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");
-
-
-
- HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
- reqistry.register("*", new WebServiceHandler());
-
-
- this.httpService = new HttpService(httpproc,
- new DefaultConnectionReuseStrategy(),
- new DefaultHttpResponseFactory());
- httpService.setParams(this.params);
- httpService.setHandlerResolver(reqistry);
-
-
- }
-
-
- @Override
- public void run() {
- System.out.println("Listening on port "
- + this.serversocket.getLocalPort());
- System.out.println("Thread.interrupted = " + Thread.interrupted());
- while (!Thread.interrupted()) {
- try {
-
- Socket socket = this.serversocket.accept();
- DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
- System.out.println("Incoming connection from "
- + socket.getInetAddress());
- conn.bind(socket, this.params);
-
-
-
- Thread t = new WorkerThread(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;
- }
- }
- }
- }
-
-
- static class WorkerThread extends Thread {
-
-
- private final HttpService httpservice;
- private final HttpServerConnection conn;
-
-
- public WorkerThread(final HttpService httpservice,
- final HttpServerConnection conn) {
- super();
- this.httpservice = httpservice;
- this.conn = conn;
- }
-
-
- @Override
- public void run() {
- System.out.println("New connection thread");
- HttpContext context = new BasicHttpContext(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 = new DefaultHttpClient();
-
- HttpGet httpGet = new HttpGet(”http:
- HttpResponse httpResponse = client.execute(httpGet);
- if (httpResponse.getStatusLine().getStatusCode() == 200) {
- response = EntityUtils.toString(httpResponse.getEntity());
- }