在之前一段的项目中,使用Java模仿Http Post方式发送参数以及文件,单纯的传递参数或者文件可以使用URLConnection进行相应的处理。

但是项目中涉及到既要传递普通参数,也要传递多个文件(不是单纯的传递XML文件)。在网上寻找之后,发现是使用HttClient来进行响应的操作,起初尝试多次依然不能传递参数和传递文件,后来发现时因为当使用HttpClient时,不能使用request.getParameter()对普通参数进行获取,而要在服务器端使用Upload来进行操作。

HttpClient4.2 jar下载 :http://download.csdn.net/detail/just_szl/4370574

客户端代码:

  1. import java.io.ByteArrayOutputStream;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import org.apache.http.HttpEntity;
  6. import org.apache.http.HttpResponse;
  7. import org.apache.http.HttpStatus;
  8. import org.apache.http.ParseException;
  9. import org.apache.http.client.HttpClient;
  10. import org.apache.http.client.methods.HttpPost;
  11. import org.apache.http.entity.mime.MultipartEntity;
  12. import org.apache.http.entity.mime.content.FileBody;
  13. import org.apache.http.impl.client.DefaultHttpClient;
  14. import org.apache.http.util.EntityUtils;
  15. /**
  16. *
  17. * @author <a href="mailto:just_szl@hotmail.com"> Geray</a>
  18. * @version 1.0,2012-6-12
  19. */
  20. public class HttpPostArgumentTest2 {
  21. //file1与file2在同一个文件夹下 filepath是该文件夹指定的路径
  22. public void SubmitPost(String url,String filename1,String filename2, String filepath){
  23. HttpClient httpclient = new DefaultHttpClient();
  24. try {
  25. HttpPost httppost = new HttpPost(url);
  26. FileBody bin = new FileBody(new File(filepath + File.separator + filename1));
  27. FileBody bin2 = new FileBody(new File(filepath + File.separator + filename2));
  28. StringBody comment = new StringBody(filename1);
  29. MultipartEntity reqEntity = new MultipartEntity();
  30. reqEntity.addPart("file1", bin);//file1为请求后台的File upload;属性
  31. reqEntity.addPart("file2", bin2);//file2为请求后台的File upload;属性
  32. reqEntity.addPart("filename1", comment);//filename1为请求后台的普通参数;属性
  33. httppost.setEntity(reqEntity);
  34. HttpResponse response = httpclient.execute(httppost);
  35. int statusCode = response.getStatusLine().getStatusCode();
  36. if(statusCode == HttpStatus.SC_OK){
  37. System.out.println("服务器正常响应.....");
  38. HttpEntity resEntity = response.getEntity();
  39. System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据
  40. System.out.println(resEntity.getContent());
  41. EntityUtils.consume(resEntity);
  42. }
  43. } catch (ParseException e) {
  44. // TODO Auto-generated catch block
  45. e.printStackTrace();
  46. } catch (IOException e) {
  47. // TODO Auto-generated catch block
  48. e.printStackTrace();
  49. } finally {
  50. try {
  51. httpclient.getConnectionManager().shutdown();
  52. } catch (Exception ignore) {
  53. }
  54. }
  55. }
  56. /**
  57. * @param args
  58. */
  59. public static void main(String[] args) {
  60. // TODO Auto-generated method stub
  61. HttpPostArgumentTest2 httpPostArgumentTest2 = new HttpPostArgumentTest2();
  62. httpPostArgumentTest2.SubmitPost("http://127.0.0.1:8080/demo/receiveData.do",
  63. "test.xml","test.zip","D://test");
  64. }
  65. }

服务端代码:

  1. public void receiveData(HttpServletRequest request, HttpServletResponse response) throws AppException{
  2. PrintWriter out = null;
  3. response.setContentType("text/html;charset=UTF-8");
  4. Map map = new HashMap();
  5. FileItemFactory factory = new DiskFileItemFactory();
  6. ServletFileUpload upload = new ServletFileUpload(factory);
  7. File directory = null;
  8. List<FileItem> items = new ArrayList();
  9. try {
  10. items = upload.parseRequest(request);
  11. // 得到所有的文件
  12. Iterator<FileItem> it = items.iterator();
  13. while (it.hasNext()) {
  14. FileItem fItem = (FileItem) it.next();
  15. String fName = "";
  16. Object fValue = null;
  17. if (fItem.isFormField()) { // 普通文本框的值
  18. fName = fItem.getFieldName();
  19. //                  fValue = fItem.getString();
  20. fValue = fItem.getString("UTF-8");
  21. map.put(fName, fValue);
  22. } else { // 获取上传文件的值
  23. fName = fItem.getFieldName();
  24. fValue = fItem.getInputStream();
  25. map.put(fName, fValue);
  26. String name = fItem.getName();
  27. if(name != null && !("".equals(name))) {
  28. name = name.substring(name.lastIndexOf(File.separator) + 1);
  29. //                      String stamp = StringUtils.getFormattedCurrDateNumberString();
  30. String timestamp_Str = TimeUtils.getCurrYearYYYY();
  31. directory = new File("d://test");
  32. directory.mkdirs();
  33. String filePath = ("d://test")+ timestamp_Str+ File.separator + name;
  34. map.put(fName + "FilePath", filePath);
  35. InputStream is = fItem.getInputStream();
  36. FileOutputStream fos = new FileOutputStream(filePath);
  37. byte[] buffer = new byte[1024];
  38. while (is.read(buffer) > 0) {
  39. fos.write(buffer, 0, buffer.length);
  40. }
  41. fos.flush();
  42. fos.close();
  43. map.put(fName + "FileName", name);
  44. }
  45. }
  46. }
  47. } catch (Exception e) {
  48. System.out.println("读取http请求属性值出错!");
  49. //          e.printStackTrace();
  50. logger.error("读取http请求属性值出错");
  51. }
  52. // 数据处理
  53. try {
  54. out = response.getWriter();
  55. out.print("{success:true, msg:'接收成功'}");
  56. out.close();
  57. } catch (IOException e) {
  58. e.printStackTrace();
  59. }
  60. }

http://blog.csdn.net/Just_szl/article/details/7659347

HttpClient通过Post上传文件(转)的更多相关文章

  1. WebAPI通过multipart/form-data方式同时上传文件以及数据(含HttpClient上传Demo)

    简单的Demo,用于了解WebAPI如何同时接收文件及数据,同时提供HttpClient模拟如何同时上传文件和数据的Demo,下面是HttpClient上传的Demo界面 1.HttpClient部分 ...

  2. [转]httpclient 上传文件、下载文件

    用httpclient4.3 post方式推送文件到服务端  准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar/** * 上传 ...

  3. 转 Android网络编程之使用HttpClient批量上传文件 MultipartEntityBuilder

    请尊重他人的劳动成果,转载请注明出处:Android网络编程之使用HttpClient批量上传文件 http://www.tuicool.com/articles/Y7reYb 我曾在<Andr ...

  4. HttpClient MultipartEntityBuilder 上传文件

    文章转载自: http://blog.csdn.net/yan8024/article/details/46531901 http://www.51testing.com/html/56/n-3707 ...

  5. HttpClient 测试web API上传文件实例

    1.使用HttpClient 测试上传文件并且设置header信息: using Lemon.Common; using Newtonsoft.Json; using System; using Sy ...

  6. Java使用HttpClient上传文件

    Java可以使用HttpClient发送Http请求.上传文件等,非常的方便 Maven <dependency> <groupId>org.apache.httpcompon ...

  7. HttpClient上传文件

    1.上传客户端代码: public static void upload() { CloseableHttpClient httpclient = HttpClients.createDefault( ...

  8. 【httpclient-4.3.1.jar】httpclient发送get、post请求以及携带数据上传文件

    1.发送get.post携带参数以及post请求接受JSON数据: package cn.qlq.utils; import java.io.BufferedReader; import java.i ...

  9. .Net使用HttpClient以multipart/form-data形式post上传文件及其相关参数

    前言: 本次要讲的是使用.Net HttpClient拼接multipark/form-data形式post上传文件和相关参数,并接收到上传文件成功后返回过来的结果(图片地址,和是否成功).可能有很多 ...

随机推荐

  1. 【读书笔记】iOS-编码对象

    Cocoa具备一种机制来将对象自身转换为某种格式并保存到磁盘中.对象可以将它们的实例变量和其他数据编码为数据块,然后保存到磁盘中.以后将这些数据块读回到内存中,并且还能基于保存的数据创建新对象.这个过 ...

  2. 【读书笔记】iOS-验证应用内支付的凭证注意事项

    1,简单来说,越狱后的手机由于没有沙盒作为保护,黑客可以对系统进行任意的修改,所以,在支付过程中,苹果返回的已付款成功的凭证可能是伪造的.客户端拿到付款凭证之后,还需要将凭证上传到自己的服务器,进行二 ...

  3. iOS开发网络篇—搭建本地服务器(待整理)

      一.简单说明 说明:提前下载好相关软件,且安装目录最好安装在全英文路径下.如果路径有中文名,那么可能会出现一些莫名其妙的问题. 提示:提前准备好的软件 apache-tomcat-6.0.41.t ...

  4. 基于AFNetWorking封装一个网络请求数据的类

    1.新建一个继承于NSObject类的类,在.h文件中 #import "AFHTTPRequestOperationManager.h" //定义两个block来接收请求成功和失 ...

  5. 大家一起和snailren学java-(七)多态

    “这个系列觉得没必要这么写,不然质量不会高,还是看一段时间,自己提炼吧” 多态,也称作动态绑定,后期绑定,是三个基本特征中非常重要的一个特征.通过多态,可以消除类型之间的耦合关系.同时多态提供了扩展程 ...

  6. Android地图开发之地图的选择

    做lbs开发差不多快2年了,地图相关的产品也差不多做了3个了,用到过的地图包括google地图.高德地图.百度地图.图吧.Osmdroid,今天总结下,方便大家开发时选择合适的地图. 首先说定位模块选 ...

  7. 常用awk命令(转)

    awk 用法:awk ' pattern {action} ' 变量名 含义 ARGC 命令行变元个数 ARGV 命令行变元数组 FILENAME 当前输入文件名 FNR 当前文件中的记录号 FS 输 ...

  8. Java 嵌套解析 json

    1.首先需要安装org.json.jar 2.类JSONObject用于创建一个json对象.其中的JSONObject.put(KEY, VALUE)用于向其中添加条目 3.JSONObject.g ...

  9. 孙鑫视频学习:改变窗口过程函数中出现error C2440错误的解决方法

    在Visual Studio 2010中,即使代码是完完全全按照孙鑫视频中的敲,也会在出现error C2440,这是因为开发平台由VC6.0升级至VS2010,需要将原有的项目迁移.VS2010对消 ...

  10. UVALive 6470 Chomp --记忆化搜索

    题意:给一个只有三行的方块阵(横向最多100个),然后p,q,r分别代表第1,2,3层的方格数,两人轮流去掉一个格子,此时这个格子的右上方都会被去掉,面临只剩最左下角的一个格子的状态的人输,问先手能否 ...