利用HttpClient以post形式上传文件
/** * created since 2012-4-6 */ package com.yonge.http; 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; /** * @author wb-gaoy * @version $Id: HttpClientTest.java,v 0.1 2012-4-6 下午1:38:53 wb-gaoy Exp $ */ public class HttpClientUploadFileTest { public void uploadFile(File file, String url) { if (!file.exists()) { return; } PostMethod postMethod = new PostMethod(url); try { //FilePart:用来上传文件的类 FilePart fp = new FilePart("filedata", file); Part[] parts = { fp }; //对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装 MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams()); postMethod.setRequestEntity(mre); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// 设置连接时间 int status = client.executeMethod(postMethod); if (status == HttpStatus.SC_OK) { System.out.println(postMethod.getResponseBodyAsString()); } else { System.out.println("fail"); } } catch (Exception e) { e.printStackTrace(); } finally { //释放连接 postMethod.releaseConnection(); } } /** * @param args */ public static void main(String[] args) { HttpClientUploadFileTest test = new HttpClientUploadFileTest(); test.uploadFile(new File("e:/default.css"), "http://ecmng.local.sit.alipay.net/receiveDevZipFile.json?summary=1010100"); } }
相关推荐
Guanjs0 2020-11-09
wmsjlihuan 2020-09-15
shishengsoft 2020-09-15
poplpsure 2020-08-17
CyborgLin 2020-08-15
Richardxx 2020-07-26
sunnyhappy0 2020-07-26
knightwatch 2020-07-19
wcqwcq 2020-07-04
chichichi0 2020-06-16
YAruli 2020-06-13
JF0 2020-06-13
84423067 2020-06-12
心丨悦 2020-06-11
zkwgpp 2020-06-04
stoneechogx 2020-06-04
litterfrog 2020-05-30
today0 2020-05-26