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
相关文章
|
消息中间件 JSON Java
Spring Boot、Spring Cloud与Spring Cloud Alibaba版本对应关系
Spring Boot、Spring Cloud与Spring Cloud Alibaba版本对应关系
24163 0
|
7天前
|
存储 关系型数据库 分布式数据库
PostgreSQL 18 发布,快来 PolarDB 尝鲜!
PostgreSQL 18 发布,PolarDB for PostgreSQL 全面兼容。新版本支持异步I/O、UUIDv7、虚拟生成列、逻辑复制增强及OAuth认证,显著提升性能与安全。PolarDB-PG 18 支持存算分离架构,融合海量弹性存储与极致计算性能,搭配丰富插件生态,为企业提供高效、稳定、灵活的云数据库解决方案,助力企业数字化转型如虎添翼!
|
6天前
|
存储 人工智能 Java
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话
本文讲解 Prompt 基本概念与 10 个优化技巧,结合学术分析 AI 应用的需求分析、设计方案,介绍 Spring AI 中 ChatClient 及 Advisors 的使用。
312 130
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话
|
18天前
|
弹性计算 关系型数据库 微服务
基于 Docker 与 Kubernetes(K3s)的微服务:阿里云生产环境扩容实践
在微服务架构中,如何实现“稳定扩容”与“成本可控”是企业面临的核心挑战。本文结合 Python FastAPI 微服务实战,详解如何基于阿里云基础设施,利用 Docker 封装服务、K3s 实现容器编排,构建生产级微服务架构。内容涵盖容器构建、集群部署、自动扩缩容、可观测性等关键环节,适配阿里云资源特性与服务生态,助力企业打造低成本、高可靠、易扩展的微服务解决方案。
1328 8
|
5天前
|
监控 JavaScript Java
基于大模型技术的反欺诈知识问答系统
随着互联网与金融科技发展,网络欺诈频发,构建高效反欺诈平台成为迫切需求。本文基于Java、Vue.js、Spring Boot与MySQL技术,设计实现集欺诈识别、宣传教育、用户互动于一体的反欺诈系统,提升公众防范意识,助力企业合规与用户权益保护。
|
17天前
|
机器学习/深度学习 人工智能 前端开发
通义DeepResearch全面开源!同步分享可落地的高阶Agent构建方法论
通义研究团队开源发布通义 DeepResearch —— 首个在性能上可与 OpenAI DeepResearch 相媲美、并在多项权威基准测试中取得领先表现的全开源 Web Agent。
1407 87
|
6天前
|
人工智能 Java API
AI 超级智能体全栈项目阶段一:AI大模型概述、选型、项目初始化以及基于阿里云灵积模型 Qwen-Plus实现模型接入四种方式(SDK/HTTP/SpringAI/langchain4j)
本文介绍AI大模型的核心概念、分类及开发者学习路径,重点讲解如何选择与接入大模型。项目基于Spring Boot,使用阿里云灵积模型(Qwen-Plus),对比SDK、HTTP、Spring AI和LangChain4j四种接入方式,助力开发者高效构建AI应用。
311 122
AI 超级智能体全栈项目阶段一:AI大模型概述、选型、项目初始化以及基于阿里云灵积模型 Qwen-Plus实现模型接入四种方式(SDK/HTTP/SpringAI/langchain4j)