2012-09-14 101 views
0

我正在使用httpCore創建我自己的基本Web服務器。一旦收到來自用戶的特定請求,就必須啓動文件傳輸操作。我用HttpRequestHandler處理請求。我的代碼看起來像這樣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(); 
     } 

    } 
}; 

這是一個非常基本的響應,但是我正在尋找一個文件從服務器傳送到客戶機。我如何發送文件作爲迴應?謝謝

回答

3

我想出了自己。如果有人遇到同樣的問題,這是我如何運作的。

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

      } 

    };