Vihaan Verma
Vihaan Verma

Reputation: 13143

HttpRequestHandler : Sending a file in response

I m working with httpCore in order to create my own basic web server. Upon receiving a certain request from the user a file transfer operation has to be initiated. I m handling the request with HttpRequestHandler. My code looks like this

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

    }
};

This is a very basic response , however What I m looking to transfer a file from the server to the client machine. How can I send a file in response ? Thanks

Upvotes: 0

Views: 2633

Answers (1)

Vihaan Verma
Vihaan Verma

Reputation: 13143

I figured it out myself. If someone stumbles across the same problem, here is how I got it working.

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

            }

    };

Upvotes: 4

Related Questions