HttpClient 发送Post请求 携带 文件 参数

1  HttpPost 请求  携带参数 同时上传文件 的关键 代码

 客户端核心代码 

	//创建HttpClient 请求
     CloseableHttpClient httpClient = HttpClients.createDefault();
	String url = "https://frt.aaa.bbb:8080/test/oneServlet";
    //创建 HttpPost
	HttpPost httpPost = new HttpPost(url);
	File file = new File("filePath");

	//创建上传文件的表单
	MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
	entityBuilder.addTextBody("test", "test");//添加普通参数
	entityBuilder.addPart("fileName",new FileBody(file));//添加上传的文件
	HttpEntity httpEntity = entityBuilder.build();
	httpPost.setEntity(httpEntity);
	//执行post 请求
	CloseableHttpResponse response = httpClient.execute(httpPost);

服务端核心代码 

       //uploadPath 服务端 存放文件的位置
       String uploadPath = getServletContext().getRealPath("/upload");
		
        //创建一个解析器工厂
		FileItemFactory factory = new DiskFileItemFactory();
         //文件上传解析器
		ServletFileUpload upload = new ServletFileUpload(factory);
		File directory = null;
		InputStream is = null;
		FileOutputStream fos = null;
        //解析请求,将表单中每个输入项封装成一个FileItem对象
		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("UTF-8");
					map.put(fName, fValue.toString());
				} else { // 获取上传文件的值
					fName = fItem.getFieldName();
					fValue = fItem.getInputStream();
					String name = fItem.getName();
					if (name != null && !("".equals(name))) {
						name = name.substring(name.lastIndexOf(File.separator) + 1);
						directory = new File(uploadPath);
						directory.mkdirs();

						// String filePath = ("d://test")+ timestamp_Str+
						// File.separator + name;
						String filePath = uploadPath + File.separator + name;

							try {
							is = fItem.getInputStream();
							fos = new FileOutputStream(filePath);
							byte[] buf = new byte[1024];
							int len = 0;
							while ((len = is.read(buf)) != -1) {
							    fos.write(buf, 0, len);
							}
							System.out.println("8");
							fos.flush();
						} catch (Exception e) {
							out.write("FAIL".getBytes());
							out.flush();
						}finally{
                            //因为 可能是多个文件上传 所以每次都关闭 不然可能 有一个IO没关 会 
                            // 导致io 一直打开 越来越占资源  服务端文件删不掉
							if(fos != null){
								fos.close();
							}
							if(is != null){
								is.close();
							}
						}
					}
				}
			}
			
			
			uploadPath = uploadPath + "\\";
			System.out.println("newPath=" + uploadPath);
			map.put("path", uploadPath);

		} catch (Exception e) {
			//System.out.println("读取http请求属性值出错!");
			 e.printStackTrace();
		} finally {
			if(is != null){
				is.close();
			}
			if(fos != null){
				fos.close();
			}			
			
		}

2 HttpClient post请求 仅仅携带参数 不携带文件

客户端核心代码

	 //创建httpClient请求
	CloseableHttpClient httpClient = HttpClients.createDefault();
	//请求地址
	String url = "https://frt.aaa.bbb:8080/test/oneServlet";
	//创建httpPost
	HttpPost httpPost = new HttpPost(url);
	//创建 参数集合
	List<NameValuePair> params = new ArrayList<NameValuePair>();
	//添加参数
	params.add(new BasicNameValuePair("str" , "str"));
	params.add(new BasicNameValuePair("str2" , "str2"));
	//将参数集合添加到httpPost
	httpPost.setEntity(new UrlEncodedFormEntity(params));	
	//执行post 请求
	CloseableHttpResponse response = httpClient.execute(httpPost);

 服务端核心

在servlet的doPost 或者 doGet中

String str= request.getParameter("str");

String str2= request.getParameter("str2");
发布了17 篇原创文章 · 获赞 7 · 访问量 5752

猜你喜欢

转载自blog.csdn.net/qq_29461579/article/details/82227566