我正在使用httpCore来创建自己的基本Web服务器。在从用户接收到某个请求时,必须启动文件传输操作。我用HttpRequestHandler处理请求。我的代码看起来像这样
private HttpRequestHandler mRequestHandler = new HttpRequestHandler()
{
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext httpContext) throws HttpException, IOException
{
try{
HttpEntity entity=null;
String contentType="text/html";
entity = new EntityTemplate(new ContentProducer()
{
public void writeTo(final OutputStream outstream)throws IOException
{
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
String resp = "Server is up and running";
writer.write(resp);
writer.flush();
}
});
((EntityTemplate)entity).setContentType(contentType);
response.setEntity(entity);
}catch(Exception e)
{
e.printStackTrace();
}
}
};
这是一个非常基本的响应,但是我希望将文件从服务器传输到客户端计算机。如何发送文件作为回应?感谢
答案 0 :(得分:4)
我自己想通了。如果有人遇到同样的问题,我就是这样做的。
private HttpRequestHandler mRequestHandler = new HttpRequestHandler()
{
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException
{
try{
File file = new File("/mnt/sdcard/Music/song.mp3");
FileEntity body = new FileEntity(file, "audio/mpeg");
response.setHeader("Content-Type", "application/force-download");
response.setHeader("Content-Disposition","attachment; filename=song.mp3");
response.setEntity(body);
}catch(Exception e)
{
e.printStackTrace();
}
}
};