HttpClient通过Post上传文件(转)
在之前一段的项目中,使用Java模仿Http Post方式发送参数以及文件,单纯的传递参数或者文件可以使用URLConnection进行相应的处理。
但是项目中涉及到既要传递普通参数,也要传递多个文件(不是单纯的传递XML文件)。在网上寻找之后,发现是使用HttClient来进行响应的操作,起初尝试多次依然不能传递参数和传递文件,后来发现时因为当使用HttpClient时,不能使用request.getParameter()对普通参数进行获取,而要在服务器端使用Upload来进行操作。
HttpClient4.2 jar下载 :http://download.csdn.net/detail/just_szl/4370574
客户端代码:
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.ParseException;
- 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.impl.client.DefaultHttpClient;
- import org.apache.http.util.EntityUtils;
- /**
- *
- * @author <a href="mailto:just_szl@hotmail.com"> Geray</a>
- * @version 1.0,2012-6-12
- */
- public class HttpPostArgumentTest2 {
- //file1与file2在同一个文件夹下 filepath是该文件夹指定的路径
- public void SubmitPost(String url,String filename1,String filename2, String filepath){
- HttpClient httpclient = new DefaultHttpClient();
- try {
- HttpPost httppost = new HttpPost(url);
- FileBody bin = new FileBody(new File(filepath + File.separator + filename1));
- FileBody bin2 = new FileBody(new File(filepath + File.separator + filename2));
- StringBody comment = new StringBody(filename1);
- MultipartEntity reqEntity = new MultipartEntity();
- reqEntity.addPart("file1", bin);//file1为请求后台的File upload;属性
- reqEntity.addPart("file2", bin2);//file2为请求后台的File upload;属性
- reqEntity.addPart("filename1", comment);//filename1为请求后台的普通参数;属性
- httppost.setEntity(reqEntity);
- HttpResponse response = httpclient.execute(httppost);
- int statusCode = response.getStatusLine().getStatusCode();
- if(statusCode == HttpStatus.SC_OK){
- System.out.println("服务器正常响应.....");
- HttpEntity resEntity = response.getEntity();
- System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据
- System.out.println(resEntity.getContent());
- EntityUtils.consume(resEntity);
- }
- } catch (ParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- try {
- httpclient.getConnectionManager().shutdown();
- } catch (Exception ignore) {
- }
- }
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- HttpPostArgumentTest2 httpPostArgumentTest2 = new HttpPostArgumentTest2();
- httpPostArgumentTest2.SubmitPost("http://127.0.0.1:8080/demo/receiveData.do",
- "test.xml","test.zip","D://test");
- }
- }
服务端代码:
- public void receiveData(HttpServletRequest request, HttpServletResponse response) throws AppException{
- PrintWriter out = null;
- response.setContentType("text/html;charset=UTF-8");
- Map map = new HashMap();
- FileItemFactory factory = new DiskFileItemFactory();
- ServletFileUpload upload = new ServletFileUpload(factory);
- File directory = null;
- List<FileItem> items = new ArrayList();
- try {
- items = upload.parseRequest(request);
- // 得到所有的文件
- Iterator<FileItem> it = items.iterator();
- while (it.hasNext()) {
- FileItem fItem = (FileItem) it.next();
- String fName = "";
- Object fValue = null;
- if (fItem.isFormField()) { // 普通文本框的值
- fName = fItem.getFieldName();
- // fValue = fItem.getString();
- fValue = fItem.getString("UTF-8");
- map.put(fName, fValue);
- } else { // 获取上传文件的值
- fName = fItem.getFieldName();
- fValue = fItem.getInputStream();
- map.put(fName, fValue);
- String name = fItem.getName();
- if(name != null && !("".equals(name))) {
- name = name.substring(name.lastIndexOf(File.separator) + 1);
- // String stamp = StringUtils.getFormattedCurrDateNumberString();
- String timestamp_Str = TimeUtils.getCurrYearYYYY();
- directory = new File("d://test");
- directory.mkdirs();
- String filePath = ("d://test")+ timestamp_Str+ File.separator + name;
- map.put(fName + "FilePath", filePath);
- InputStream is = fItem.getInputStream();
- FileOutputStream fos = new FileOutputStream(filePath);
- byte[] buffer = new byte[1024];
- while (is.read(buffer) > 0) {
- fos.write(buffer, 0, buffer.length);
- }
- fos.flush();
- fos.close();
- map.put(fName + "FileName", name);
- }
- }
- }
- } catch (Exception e) {
- System.out.println("读取http请求属性值出错!");
- // e.printStackTrace();
- logger.error("读取http请求属性值出错");
- }
- // 数据处理
- try {
- out = response.getWriter();
- out.print("{success:true, msg:'接收成功'}");
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
http://blog.csdn.net/Just_szl/article/details/7659347
HttpClient通过Post上传文件(转)相关推荐
- java上传文件到远程服务器(一)---HttpURLConnection方式
我们在之前的文章 JavaWeb静态资源分离思路 中已经了解到要把文件上传到静态资源服务器有三种方式: java上传文件到ftp服务器(这个方案需要在静态资源服务器安装ftp服务) java使用Htt ...
- tomcat上传文件偶见异常
我的服务为数据接收服务,上传文件也是由程序模拟上传,是由httpclient写的上传文件,因为本身上传的时候并没有在程序中设置请求超时时间,所以在接收的服务中就会发现了如下的错误: org.apach ...
- httpclient通过POST来上传文件,而不是通过流的形式,并在服务端进行解析(通过htt......
为什么80%的码农都做不了架构师?>>> package url;import io.IoStreamUtil;import java.io.File; import java ...
- java http 上传文件_java利用httpClient实现后台文件上传请求
之前写过基于html和js的文件上传方法java 用springMVC 和HttpServletRequest 两种实现文件上传的方法和httpClient后台执行普通post请求的文章java通过h ...
- [转]httpclient 上传文件、下载文件
用httpclient4.3 post方式推送文件到服务端 准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar/*** 上传文件 ...
- 使用HttpClient MultipartEntityBuilder 上传文件,并解决中文文件名乱码问题
使用HttpClient MultipartEntityBuilder 上传文件,并解决中文文件名乱码问题 参考文章: (1)使用HttpClient MultipartEntityBuilder 上 ...
- java httpclient 下载文件_httpclient 上传文件、下载文件
/** * 上传文件 * @throws ParseException * @throws IOException */ publicstaticvoidpostFile()throwsParse ...
- C# 使用HttpClient上传文件并附带其他参数的步骤
HttpClient和MultipartFormDataContent(传送门)最低适用于.NET Framework 4.5版本 发送端代码 using (HttpClient client = n ...
- HttpClient上传文件传入MultipartFile类型
通常我们在使用httpclient的时候,一把都是使用get或者postd的方式传输一些数据.在近期的项目中有这样的一个需求,我需要通过httpclient去调用一个写好的文件上传的接口,接口中是使用 ...
最新文章
- 快手:魔性BGM你把握不住的,让AI来
- 谁干的mysql无密码登录?
- hiho_1050_树中的最长路
- 信息化监理公司的所有问题归到底是人的使用和管理
- java 获取字符串长度_ava练习实例:java字符串长度与Java String charAt() 方法 (建议收藏)...
- 若要加载模块二进制_春哥说 | 浅谈NodeJs的模块机制-2
- linux无法访问mysql_Linux下MySQL无法访问问题排查的基本步骤
- transform再次理解
- UI学习笔记---EasyUI panel插件使用---03
- eclipse 装配server时找不到tomcat
- Linux服务器性能的重要指标:打开文件数的限制
- java语言的编译器命令_Java编译器命令行功能
- 清华学生的编程能力有多强?大一学生 C++作业引爆全网,特奖得主、阿里P6:我们也做不到...
- 云计算:吹尽狂沙始到金
- Android的资源引用(2)(Drawable)
- vscode配置c语言并优化
- 双向链表 建立和插入
- (迁)rsync:基本命令和用法
- ASPICE_SWE.1_01_02_SQ3RNote
- 全基因组多位点序列分型
热门文章
- org.hibernate.LazyInitializationException: could not initialize proxy - no Session
- leetcode74. 搜索二维矩阵 ,你见过吗
- 危险!!!也许你的web网站或服务正在悄无声息地被SQL注入
- 内核中的 likely() 与 unlikely()
- 深度学习(莫烦 神经网络 lecture 3) Keras
- python用pip安装pillow_cent 6.5使用pip安装pillow总是失败
- JAVA 程序执行进行计时,用于验证程序执行的时间
- 英语口语 week11 Tuesday
- Java基础 —— JVM内存模型与垃圾回收
- 切记!这样洗头最伤身