Search code examples
androidbrowserfile-uploadwebserverhttpservice

android httpservice upload file from browser


I have created http service on android. And now I want to upload the file from browser to server (android). Let's look what I've done:

private static final String ALL_PATTERN = "*";
private static final String UPLOADFILE_PATTERN = "/UploadFile/*";
/* Some variables */
public WebServer(Context context) {
    this.setContext(context);
    httpproc = new BasicHttpProcessor();
    httpContext = new BasicHttpContext();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());
    httpService = new HttpService(httpproc,
        new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory());
    registry = new HttpRequestHandlerRegistry();
    registry.register(ALL_PATTERN, new HomeCommandHandler(context));        
    registry.register(UPLOADFILE_PATTERN, new UploadCommandHandler(context));       
    httpService.setHandlerResolver(registry);
}

Then I write url in browser (for example http://127.0.0.1:6789/home.html (I play with emulator)). Http service sends me form like below:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>File Upload</title>
</head>
<body>
<form method="POST" action="UploadFile/" enctype="multipart/form-data">
<p>File1 Test:
<input type="file" name="myfile1" size="20">
<input type="submit" value="Upload file">
<input type="reset" value="Reset" name="someName">  
</form>
</body>

I choose some file and press submit. After that the server invoke this method:

 @Override
public void handle(HttpRequest request, HttpResponse response,
    HttpContext httpContext) throws HttpException, IOException {

    Log.e("","INSIDE UPLOADER");
    Log.e("Method",request.getRequestLine().getMethod());
    Log.e("len",request.getRequestLine()+"");
    for(Header h : request.getAllHeaders()){
        Log.e("len", h.getName()+" = "+h.getValue()); 
    }
}

It returns in LogCat:

Content-Length = 4165941
Content-Type = multipart/form-data; boundary=----WebKitFormBoundarykvmpGbpMd6NM1Lbk
Method POST /UploadFile/ HTTP/1.1

and other parameters. My question is where can I get the file content? I mean some InputStream or something else. I know HttpResponse has method like getContent(). But HttpRequest has no this one. Thanks.


Solution

  • If the HttpRequest contains an entity it should also implement HttpEntityEnclosingRequest. This goes in your #handle(HttpRequest request, HttpResponse response) method:

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null) {
            // Now you can call entity.getContent() and do your thing
        }
    }