Sunday, September 18, 2011

Android - Integrate Jetty Server In Your Application

First Add the following 6 JARs in your project
Import the following packages:

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;

then Add the following Function:

public static final int SERVERPORT = 1234;

Handler handler = new AbstractHandler()
public void handle(String target, Request request, HttpServletRequest MainRequestObject,
HttpServletResponse response) throws IOException, ServletException
//How to get Query String/
Log.i("Query String", target);

//URI format

//Http Request Type: GET/POST/PUT/DELETE
Log.i("HTTP Verb", MainRequestObject.getMethod());

BufferedReader in = new BufferedReader(new InputStreamReader(MainRequestObject.getInputStream()));
String line = null;
StringBuilder PostedData = new StringBuilder();

while ((line = in.readLine()) != null)
Log.i("Received Message Line by Line", line);

//Http Request Data Type
Log.i("Posted Data Type", MainRequestObject.getContentType());

//Http Request Type: GET/POST/PUT/DELETE
Log.i("Posted Data", PostedData.toString());

//How To Send Responce Back
        catch (Exception ex)
        Log.i("Error", ex.getMessage());

In "onCreate" function:

Server server = new Server(SERVERPORT);

*Now you can handle all the HTTP request from with-in your android app.