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上传文件(转)的更多相关文章
- WebAPI通过multipart/form-data方式同时上传文件以及数据(含HttpClient上传Demo)
简单的Demo,用于了解WebAPI如何同时接收文件及数据,同时提供HttpClient模拟如何同时上传文件和数据的Demo,下面是HttpClient上传的Demo界面 1.HttpClient部分 ...
- [转]httpclient 上传文件、下载文件
用httpclient4.3 post方式推送文件到服务端 准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar/** * 上传 ...
- 转 Android网络编程之使用HttpClient批量上传文件 MultipartEntityBuilder
请尊重他人的劳动成果,转载请注明出处:Android网络编程之使用HttpClient批量上传文件 http://www.tuicool.com/articles/Y7reYb 我曾在<Andr ...
- HttpClient MultipartEntityBuilder 上传文件
文章转载自: http://blog.csdn.net/yan8024/article/details/46531901 http://www.51testing.com/html/56/n-3707 ...
- HttpClient 测试web API上传文件实例
1.使用HttpClient 测试上传文件并且设置header信息: using Lemon.Common; using Newtonsoft.Json; using System; using Sy ...
- Java使用HttpClient上传文件
Java可以使用HttpClient发送Http请求.上传文件等,非常的方便 Maven <dependency> <groupId>org.apache.httpcompon ...
- HttpClient上传文件
1.上传客户端代码: public static void upload() { CloseableHttpClient httpclient = HttpClients.createDefault( ...
- 【httpclient-4.3.1.jar】httpclient发送get、post请求以及携带数据上传文件
1.发送get.post携带参数以及post请求接受JSON数据: package cn.qlq.utils; import java.io.BufferedReader; import java.i ...
- .Net使用HttpClient以multipart/form-data形式post上传文件及其相关参数
前言: 本次要讲的是使用.Net HttpClient拼接multipark/form-data形式post上传文件和相关参数,并接收到上传文件成功后返回过来的结果(图片地址,和是否成功).可能有很多 ...
随机推荐
- nib文件的注册及加载
1,注册 [(UIView *)view registerNib:[UINib nibWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle ...
- git学习笔记1
很早以前就听说了git,今天就开始使用git,并做简单记录 在Linux上安装Git 首先,你可以试着输入git,看看系统有没有安装Git: $ git The program 'git' is cu ...
- UIStoryBoard 中修改控件borderColor
storyBoard中直接修改UI控件的边框颜色,可以避免先关联再从控制器中修改属性等繁琐操作 因为layer.borderColor隶属于CALayer对象,且CGColor无法直接在sb中直接使用 ...
- IOS 应用跳转 (IOS9白名单)
跳转到指定app的实现 IOS中应用的跳转是通过URL实现的,因此在实现应用跳转之前我们要设置一下对应的URL. 图一(寻找配置软件的URL) 图二(具体配置选项) 注意: 如果IOS版本为IOS9 ...
- iOS-多线程之NSOperation
前言 这篇文章主要讲NSOperation的使用. What 使用NSOperation和NSOperationQueue进行多线程开发类似于线程池,只要将一个NSOperation(实际开发中需要使 ...
- Java之fianl修饰符
fianl修饰的变量不可以改变,一旦获得初始值,该final变量的值就不能被重新赋值. 1.final成员变量(必需由程序员显式地指定初始值) 类变量:必须在静态初始化块中或者声明该变量时指定初始值, ...
- Atitit.一个cms有多少少扩展点,多少api wordpress cms有多少api。。扩展点
Atitit.一个cms有多少少扩展点,多少api wordpress cms有多少api..扩展点 1. Api分类 WordPress APIs1 1.1. 1 函数分类2 1.2. 函数api ...
- SQL之 CAST 和 CONVERT
原文来自于: http://bbs.csdn.net/topics/330251394 CAST 和 CONVERT将某种数据类型的表达式显式转换为另一种数据类型.CAST 和 CONVERT 提供相 ...
- Force.com平台基础--前言
云计算平台 云计算模式有三种:(下面介绍来自百科) 1. SaaS:提供给客户的服务是运营商运行在云计算基础设施上的应用程序,用户可以在各种设备上通过客户端界面访问,如浏览器.消费者不需要管理或控制任 ...
- ehcache入门
一.简介 ehcache是一个开源的,纯java进程内的缓存框架.它具有快速,简单,具有多种缓存策略等特点. Hibernate中默认就是用了ehcache.在我们的应用中使用ehcache可以快速地 ...