Java 利用HttpClient进行http文件上传
2018-07-20 来源:open-open
应用程序部分:注意:要载入commons-httpclient-3.1.jar commons-codec.jar commons- logging.jar这三个包
Hclient.java
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(); } } }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:java获得PID
下一篇:Java实现Grep
最新资讯
热门推荐