HttpClient通过Post上传文件(转)

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

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

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

客户端代码:

[java] view plain copy

  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:[email protected]"> 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. }

服务端代码:

[java] view plain copy

  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

时间: 2024-08-25 07:55:04

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

Xamarin.Forms 使用HttpClient上传文件

Xamarin.Forms 使用HttpClient上传文件 在应用开发中,上传图片很多时候都是不可避免的问题: 以下用HttpClient实现的上传文件代码: 1 public static async Task<string> UploadFileAsync(string url ,string path) 2 { 3 using (var client = new HttpClient()) 4 { 5 using (var content = new MultipartFormData

Android网络编程之使用HttpClient批量上传文件

请尊重他人的劳动成果,转载请注明出处:Android网络编程之使用HttpClient批量上传文件 我曾在<Android网络编程之使用HTTP访问网络资源>一文中介绍过HttpCient的使用,这里就不在累述了,感兴趣的朋友可以去看一下.在这里主要介绍如何通过HttpClient实现文件上传. 1.预备知识: 在HttpCient4.3之前上传文件主要使用MultipartEntity这个类,但现在这个类已经不在推荐使用了.随之替代它的类是MultipartEntityBuilder. 下面

Android网络编程之使用HttpClient批量上传文件(二)AsyncTask+HttpClient并实现上传进度监听

请尊重他人的劳动成果,转载请注明出处: Android网络编程之使用HttpClient批量上传文件(二)AsyncTask+HttpClient并实现上传进度监听 运行效果图: 我曾在<Android网络编程之使用HttpClient批量上传文件>一文中介绍过如何通过HttpClient实现多文件上传和服务器的接收.在上一篇主要使用Handler+HttpClient的方式实现文件上传.这一篇将介绍使用AsyncTask+HttpClient实现文件上传并监听上传进度. 监控进度实现: 首先

HttpClient上传文件

今天在写微信的多媒体上传下载接口,当时无论采用哪一个API都无法提交正确提交数据过去,不是连接不了微信服务器,就是微信服务器返回数据错误,后台百度了下,找到一篇文章,但不是用HttpClient写的,他是直接用jdk自带的URLConnection提交的数据.初看之下,想想HttpClient应该也可以做到的,也就仿照了下那哥们组装了下数据尝试下,用了StringEntity.FileEntity.InputStreamEntity都无法正确提交数据.后来出去抽了支烟,理清下思路.重写来过,结果

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

简单的Demo,用于了解WebAPI如何同时接收文件及数据,同时提供HttpClient模拟如何同时上传文件和数据的Demo,下面是HttpClient上传的Demo界面 1.HttpClient部分: HttpClient通过PostAsync提交数据时,第二个请求参数为抽象类HttpContent,当前我们需要通过multipart/form-data的方式模拟请求,multipart对应的请求HttpContent为MultipartContent及其子类MultipartFormData

httpclient 4.3 psot方法上传文件与参数 中文乱码解决

废话不多说,直接上有码的! 1 package httpclient; 2 3 import java.io.File; 4 import java.nio.charset.Charset; 5 6 import org.apache.http.Consts; 7 import org.apache.http.Header; 8 import org.apache.http.HttpEntity; 9 import org.apache.http.client.methods.Closeable

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

用httpclient4.3 post方式推送文件到服务端  准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar/** * 上传文件 * @throws ParseException * @throws IOException */ publicstaticvoidpostFile()throwsParseException, IOException{ CloseableHttpClient httpClient = Htt

网络编程之使用HttpClient上传文件的客户端和服务器

1.1客户端: HttpClient常用HttpGet和HttpPost这两个类,分别对应Get方式和Post方式. 无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源. 1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象. 2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象. 3.通过HttpResp

httpclient 上传文件、下载文件

用httpclient4.3 post方式推送文件到服务端   准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar 标签: <无> 代码片段(1)[全屏查看所有代码] 1. [代码][Java]代码 /**  * 上传文件  * @throws  ParseException  * @throws  IOException  */    publicstaticvoidpostFile()throwsParseExcept