2013-12-19 36 views
4

我正在使用回答here嘗試進行數據上傳的POST請求,但我對服務器端有不尋常的要求。該服務器是一個PHP腳本,在Content-Disposition行上需要filename,因爲它期望文件上傳。如何使用Apache httpclient獲得自定義Content-Disposition行?

Content-Disposition: form-data; name="file"; filename="-" 

然而,在客戶端,我想發佈一個內存緩衝區(在這種情況下,一個字符串),而不是一個文件,而是在服務器進程它,就好像它是一個文件上傳。

但是,使用StringBody我不能在Content-Disposition行添加所需的filename字段。因此,我嘗試使用FormBodyPart,但這只是將filename放在一個單獨的行上。

HttpPost httppost = new HttpPost(url); 
MultipartEntity entity = new MultipartEntity(); 
ContentBody body = new StringBody(data,        
     org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM); 
FormBodyPart fbp = new FormBodyPart("file", body); 
fbp.addField("filename", "-");      
entity.addPart(fbp);        
httppost.setEntity(entity);    

我怎樣才能得到一個filename進入Content-Disposition線,無需先寫我String成一個文件,然後回讀出來呢?

回答

4

試試這個

StringBody stuff = new StringBody("stuff"); 
FormBodyPart customBodyPart = new FormBodyPart("file", stuff) { 

    @Override 
    protected void generateContentDisp(final ContentBody body) { 
     StringBuilder buffer = new StringBuilder(); 
     buffer.append("form-data; name=\""); 
     buffer.append(getName()); 
     buffer.append("\""); 
     buffer.append("; filename=\"-\""); 
     addField(MIME.CONTENT_DISPOSITION, buffer.toString()); 
    } 

}; 
MultipartEntity entity = new MultipartEntity(); 
entity.addPart(customBodyPart); 
1

作爲清潔替代方法來創建一個額外的匿名內部類,並增加副作用的保護方法,使用FormBodyPartBuilder

​​
相關問題