閱讀632 返回首頁    go 阿裏雲 go 技術社區[雲棲]


HttpClient4 文件上傳

httpclient上傳文件實際上就是模擬一個http的表單提交請求。 
Java代碼  收藏代碼
  1. package test.httpclient4;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5.   
  6. import org.apache.http.HttpEntity;  
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.HttpStatus;  
  9. import org.apache.http.client.ClientProtocolException;  
  10. import org.apache.http.client.HttpClient;  
  11. import org.apache.http.client.methods.HttpPost;  
  12. import org.apache.http.entity.mime.MultipartEntity;  
  13. import org.apache.http.entity.mime.content.FileBody;  
  14. import org.apache.http.entity.mime.content.StringBody;  
  15. import org.apache.http.impl.client.DefaultHttpClient;  
  16. import org.apache.http.util.EntityUtils;  
  17.   
  18. public class SendFile {  
  19.   
  20.     public static void main(String[] args) throws ClientProtocolException,  
  21.             IOException {  
  22.         HttpClient httpclient = new DefaultHttpClient();  
  23.         //請求處理頁麵  
  24.         HttpPost httppost = new HttpPost(  
  25.                 "https://localhost:8080/webtools/upload.jsp");  
  26.         //創建待處理的文件  
  27.         FileBody file = new FileBody(new File("d:/22.rar"));  
  28.         //創建待處理的表單域內容文本  
  29.         StringBody descript = new StringBody("0431.la");  
  30.   
  31.         //對請求的表單域進行填充  
  32.         MultipartEntity reqEntity = new MultipartEntity();  
  33.         reqEntity.addPart("file", file);  
  34.         reqEntity.addPart("descript", descript);  
  35.         //設置請求  
  36.         httppost.setEntity(reqEntity);  
  37.         //執行  
  38.         HttpResponse response = httpclient.execute(httppost);  
  39.         //HttpEntity resEntity = response.getEntity();  
  40.         //System.out.println(response.getStatusLine());  
  41.         if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){  
  42.             HttpEntity entity = response.getEntity();  
  43.             //顯示內容  
  44.             if (entity != null) {  
  45.                 System.out.println(EntityUtils.toString(entity));  
  46.             }  
  47.             if (entity != null) {  
  48.                 entity.consumeContent();  
  49.             }  
  50.         }  
  51.     }  
  52. }  

這裏說明一下 需要一個額外的包,apache 的mime4j 的lib。 

最後更新:2017-04-03 22:30:58

  上一篇:go Python多線程下載有聲小說
  下一篇:go 用commons的HttpClient和FileUpload寫的文件上傳下載類