Search code examples
androidparsinghttp-request

Parse incoming http post request java android


I am working on an Android web server.When i go to localhost:8080 on the emulator browser, it serves a page/form with a password field. On successful verification of the password, I would like to redirect the user to the success/failure page.What would be the best way to read the incoming http post request and parse the password field for verification?Any pointers in the right direction would be greatly appreciated. I have a handler for the url to which the form is submitted. The code for the handler is:

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;

import android.content.Context;

public class LoginHandler implements HttpRequestHandler {
private Context context = null;
public LoginHandler(Context context) {
    this.context = context;
}

@Override
public void handle(final HttpRequest request, HttpResponse response,
        HttpContext httpcontext) throws HttpException, IOException {
       HttpEntity entity = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            String resp = null;
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            if(validatePassword()==true){
             resp ="<html><head></head><body><h1>Home<h1><p>Success.</p></body></html>";
            }
            else{resp="<html><head></head><body><h1>Home<h1><p>Login Failed.</p></body></html>";}
            writer.write(resp);
            writer.flush();
        }


    });
    response.setHeader("Content-Type", "text/html");
    response.setEntity(entity);

}
boolean validatePassword(){
boolean pass=false;
//parse request body here and check for the password if true return true/else false
 return pass;
 }


 }

Solution

  • After looking around for ages I found the solution. Adding the following in the handle method does the trick.Thanks to the original poster .http://www.androiddevblog.net/android/a-bare-minimum-web-server-for-android-platform

            if (request instanceof HttpEntityEnclosingRequest) {
    HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
    if (entity != null) {
    Log.v("RequestBody", EntityUtils.toString(entity, "UTF-8"));
    entity.consumeContent();
    }
    }