2012-03-06 117 views
0

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

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

如果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 
    } 
} 
+0

谢谢。我明天会试试! – Nolesh 2012-03-06 14:19:25