android httpservice从浏览器上传文件

时间:2012-03-06 12:16:12

标签: android browser file-upload webserver httpservice

我在android上创建了http服务。现在我想将文件从浏览器上传到服务器(android)。让我们看看我做了什么:

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);
}

然后我在浏览器中写入url(例如http://127.0.0.1:6789/home.html(我玩模拟器))。 Http服务发送给我的形式如下:

<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>

我选择了一些文件并按提交。之后,服务器调用此方法:

 @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()); 
    }
}

它返回LogCat:

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

等参数。 我的问题是我在哪里可以获得文件内容?我的意思是一些InputStream或其他东西。我知道HttpResponse有像getContent()这样的方法。但是HttpRequest没有这个。 谢谢。

1 个答案:

答案 0 :(得分:1)

如果HttpRequest包含实体,则还应实施HttpEntityEnclosingRequest。这适用于#handle(HttpRequest request, HttpResponse response)方法:

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
    }
}