HttpClient4 文件上傳
httpclient上傳文件實際上就是模擬一個http的表單提交請求。- package test.httpclient4;
- import java.io.File;
- import java.io.IOException;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.entity.mime.MultipartEntity;
- import org.apache.http.entity.mime.content.FileBody;
- import org.apache.http.entity.mime.content.StringBody;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.util.EntityUtils;
- public class SendFile {
- public static void main(String[] args) throws ClientProtocolException,
- IOException {
- HttpClient httpclient = new DefaultHttpClient();
- //請求處理頁麵
- HttpPost httppost = new HttpPost(
- "https://localhost:8080/webtools/upload.jsp");
- //創建待處理的文件
- FileBody file = new FileBody(new File("d:/22.rar"));
- //創建待處理的表單域內容文本
- StringBody descript = new StringBody("0431.la");
- //對請求的表單域進行填充
- MultipartEntity reqEntity = new MultipartEntity();
- reqEntity.addPart("file", file);
- reqEntity.addPart("descript", descript);
- //設置請求
- httppost.setEntity(reqEntity);
- //執行
- HttpResponse response = httpclient.execute(httppost);
- //HttpEntity resEntity = response.getEntity();
- //System.out.println(response.getStatusLine());
- if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
- HttpEntity entity = response.getEntity();
- //顯示內容
- if (entity != null) {
- System.out.println(EntityUtils.toString(entity));
- }
- if (entity != null) {
- entity.consumeContent();
- }
- }
- }
- }
這裏說明一下 需要一個額外的包,apache 的mime4j 的lib。
最後更新:2017-04-03 22:30:58