通過HttpClient實現http上傳文件

wgd7 9年前發布 | 1K 次閱讀 Java

注意:要載入commons-httpclient-3.1.jar commons-codec.jar commons-logging.jar這三個包

import java.io.File;

import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part;

public class Hclient { public static void main(String args[]) { String targetURL = null;// TODO 指定URL File targetFile = null;// TODO 指定上傳文件

targetFile = new File("1.mp3"); targetURL = "http://localhost:8080/test/tt"; //servleturl PostMethod filePost = new PostMethod(targetURL);

try {

//通過以下方法可以模擬頁面參數提交
//filePost.setParameter("name", "中文");
//filePost.setParameter("pass", "1234");

Part[] parts = { new FilePart(targetFile.getName(), targetFile) }; filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { System.out.println("上傳成功"); // 上傳成功 } else { System.out.println("上傳失敗"); // 上傳失敗 } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } } }</pre>

 本文由用戶 wgd7 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!