`
sharron5
  • 浏览: 18499 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

https+spring3+httpclient4多文件上传

阅读更多
本文章主要介绍使用httpclient通过HTTPS加密上传文件。
为了比较好理解,由两个工程来实现这个功能:
服务端:multiuploadserver

服务端证书生成及配置可参考我之前的博客:
JAVA keytool数字证书生成及应用
需要注意的是,在生成keystore时:‘CN(Common Name名字与姓氏)’ 的值必须与服务端URL中的名称一致。
比如所访问的服务器端的URL为:https://localhost:8443/test,则CN值必须为localhost。

配置完成后,就可编写服务端代码了(这部分可参考spring3.0多文件上传
只要在此spring3.0多文件上传基础上加入web.xml配置即可(这个在JAVA keytool数字证书生成及应用中已有说明):
<security-constraint>
		<web-resource-collection>
			<web-resource-name>HtmlAdaptor</web-resource-name>			
			<url-pattern>/</url-pattern>			
		</web-resource-collection>		
		<user-data-constraint>
			<description>Protection should be CONFIDENTIAL</description>
			<transport-guarantee>CONFIDENTIAL</transport-guarantee>
		</user-data-constraint>
	</security-constraint>



客户端:multiuploadClient

客户端操作:

首先访问服务器URL(基于IE),会提示安装证书,点击‘查看证书’--》‘详细信息’--》复制到文件。将证书保存到本地。
此处导出位置为multiuploadClient工程src目录下,证书文件名为multi.cer。

然后进入命令行窗口(确定配置好了JAVA环境):
(1) cd 保存的证书所在目录
(2) 输入:keytool -import -keystore client.keystore -storepass 111111 -alias client -file multi.cer
storepass必须证书密码一致。
正确导入证书之后,就可编写代码了:
package com.client.ctl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import java.security.KeyStoreException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;

public class UploadFileCtl {


	HttpClient httpClient = new DefaultHttpClient();

	MultipartEntity multipartEntity = new MultipartEntity();	

	/**
	 * getHttpClient
	 * @return
	 */
	public HttpClient getHttpClient() {
		return httpClient;
	}

	/**
	 * getMultipartEntity
	 * @return
	 */
	public MultipartEntity getMultipartEntity() {
		return multipartEntity;
	}	

	/**
	 * 获得KeyStore
	 * @param uri
	 * @param storepass
	 * @return
	 */
	public KeyStore getKeyStore(String uri, String storepass) {
		System.out.println("getKeyStore****************");
		KeyStore keyStore = null;
		try {
			keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		} catch (KeyStoreException e) {
			e.printStackTrace();
			System.out.println("Failed to create keystore");
		}
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(uri);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("File read exception");
		}
		try {
			keyStore.load(fis, storepass.toCharArray());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return keyStore;
	}

	/**
	 * 获得SocketFactory
	 * @param keyStore
	 * @return
	 */
	public SocketFactory getSocketFactory(KeyStore keyStore) {
		System.out.println("getSocketFactory****************");
		SocketFactory socketFactory = null;
		try {
			socketFactory = new SSLSocketFactory(keyStore);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return socketFactory;
	}

	/**
	 * 配置连接信息
	 * @param name
	 * @param SocketFactory
	 * @param port
	 */
	public void registryScheme(String name, SocketFactory SocketFactory,
			int port) {
		System.out.println("registryScheme****************");
		Scheme scheme = new Scheme(name, SocketFactory, port);
		httpClient.getConnectionManager().getSchemeRegistry().register(
				scheme);
	}

	/**
	 * 获得HttpPost
	 * @param uri
	 * @return
	 */
	public HttpPost getHttpPost(String uri) {
		System.out.println("getHttpPost****************");
		HttpPost httpPost = new HttpPost(uri);
		System.out.println("executing request:" + httpPost.getRequestLine());
		return httpPost;
	}

	/**
	 * 添加文件主体
	 * @param name
	 * @param fileBody
	 */
	public void addFileBody(String[] name ,FileBody[] fileBody) {		
		for (int i = 0; i < name.length; i++) {
			System.out.println("addContentBody:"+name[i]);
			multipartEntity.addPart(name[i], fileBody[i]);
		}		
	}

	/**
	 * 设置请求实体multipartEntity
	 * @param httpPost
	 */
	public void setEntity(HttpPost httpPost) {
		System.out.println("setEntity****************");
		httpPost.setEntity(multipartEntity);
	}

	/**
	 * 执行请求
	 * @param httpUriRequest
	 * @return
	 */
	public HttpResponse executeRequest(HttpUriRequest httpUriRequest) {
		System.out.println("executeRequest****************");
		HttpResponse httpresponse = null;
		try {
			httpresponse = httpClient.execute(httpUriRequest);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpresponse;
	}

	/**
	 * 关闭连接,释放所有资源
	 */
	public void closeConnection() {
		System.out.println("closeConnection****************");
		httpClient.getConnectionManager().shutdown();
	}

	public static void main(String[] args) {
		UploadFileCtl ufc = new UploadFileCtl();		
		KeyStore keyStore = ufc.getKeyStore(
				"G:/workspace/multiuploadClient/src/client.keystore", "111111");		
		SocketFactory socketFactory = ufc.getSocketFactory(keyStore);		
		ufc.registryScheme("https", socketFactory, 8443);
		HttpPost httpPost = ufc
				.getHttpPost("https://localhost:8443/multiuploadserver/multiuploadController/uploadFile");
		ufc.addFileBody(
				new String[]{"file","file"},
				new FileBody[]{
				new FileBody(new File("G:/workspace/multiuploadClient/src/multi.cer")),
				new FileBody(new File("G:/workspace/multiuploadClient/src/client.keystore"))
				}
				);
		ufc.setEntity(httpPost);
		
		/***********************************************************************/
		
		HttpResponse httpresponse = ufc.executeRequest(httpPost);
		ufc.closeConnection();
		System.out.println("\n-------------------------------------------------------------\n");
		HttpEntity httpentity = httpresponse.getEntity();
		
		System.out.println("StatusLine:" + httpresponse.getStatusLine());
		if (httpentity != null) {
			System.out.println("------------------Response content start------------------------");
			try {
				InputStream in = httpentity.getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(in));
				String str;
				while ((str = br.readLine()) != null) {
					System.out.println(str);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("--------------------Response content end----------------------");
			System.out.println("Response Content-Type: "
					+ httpentity.getContentType());
			try {
				httpentity.consumeContent();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
}


代码完成后,首先将multiuploadserver工程部署到JBOSS下,启动JBOSS,然后运行客户端代码即可。
分享到:
评论

相关推荐

    spring-aop-2.5.6.jar,jfreechart-1.0.13.jar,commons-fileupload.jar,

    commons总包+spring总包+常用包.rar,jstl,图表,日志,文件上传,httpclient请求方式

    基于Spring MVC的web框架 1.1.11

    版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 Word工具类 Java NIO实现socket工具类 分布式session jdk升级到1.7 嵌入式redis服务(只支持linux) ...

    基于Dubbo实现的SOA分布式(没有实现分布式事务)-SpringBoot整合各种组件的JavaWeb脚手架+源代码+文档

    - 文件上传 - 文件下载 ## 邮件模块 - 单独发送邮件 - 群发邮件 - Thymeleaf邮件模板 ## 安全模块 - 注解形式的权限校验 - 拦截器 ## 文章管理模块 - 增改删查 # 整合注意点 1. 每个Mapper上都要加@Mapper...

    接口开发、springboot、接口转发、前端直接调用图床API时我们发现会报错,编写一个后端接口进行代理即可解决,已实现的例子

    以下是一个基于`RestTemplate`转发文件上传请求到目标服务的示例 主要运用了以下技术: 1. Spring MVC框架 构建Web应用程序 2. Apache HttpClient库 模拟请求API接口 3. MultipartEntityBuilder 将上传相关参数以...

    培训体系管理系统-oracle-ssh

    上传的lib包中需要加入以下文件,因为容量过大,没有上传,请见谅! antlr-2.7.6.jar antlr-2.7.6rc1.jar aopalliance.jar asm.jar asm-attrs.jar asm-commons-2.2.3.jar asm-util-2.2.3.jar aspectjrt.jar ...

    SpringMVC基础上的web框架

    版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 Word工具类 Java NIO实现socket工具类 分布式session jdk升级到1.7 嵌入式redis服务(只支持linux) ...

    基于SpringMVC的一个web框架

    版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 Word工具类 Java NIO实现socket工具类 分布式session jdk升级到1.7 嵌入式redis服务(只支持linux) ...

    JAVA上百实例源码以及开源项目

    2个目标文件,FTP的目标是:(1)提高文件的共享性(计算机程序和/或数据),(2)鼓励间接地(通过程序)使用远程计算机,(3)保护用户因主机之间的文件存储系统导致的变化,(4)为了可靠和高效地传输,虽然用户...

    一个可以直接运行的基于SpringMVC的web框架1.1.12

    版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 Word工具类 Java NIO实现socket工具类 分布式session jdk升级到1.7 嵌入式redis服务(只支持linux) ...

    Java源码 SpringMVC Mybatis Shiro Bootstrap Rest Webservice

    4. 文件上传、多线程下载服务化、发送邮件、短信服务化、部门信息服务化、产品信息服务化、信息发布服务化、我的订阅服务化、我的任务服务化、公共链接、我的收藏服务化等 系统模块: 1. 用户管理: 用户信息...

    可以直接运行的基于SpringMVC的web框架示例,也可以直接当公司框架

    版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 Word工具类 Java NIO实现socket工具类 分布式session jdk升级到1.7 嵌入式redis服务(只支持linux) ...

    java开源包4

    Java文件上传组件 COS FAT文件系统读写类库 fat32-lib fat32-lib 是一个用来读写 FAT 16/32 格式文件系统的纯 Java 类库(纯的)。 Eclipse的HTML格式化插件 Eclipse Tidy Eclipse HTML Tidy 是一款 Eclipse 的...

    java开源包3

    Java文件上传组件 COS FAT文件系统读写类库 fat32-lib fat32-lib 是一个用来读写 FAT 16/32 格式文件系统的纯 Java 类库(纯的)。 Eclipse的HTML格式化插件 Eclipse Tidy Eclipse HTML Tidy 是一款 Eclipse 的...

    基于SSM框架的SOA架构电商商城+源代码+文档说明

    - Spring、SpringMVC、Mybatis 基本框架 - MySQL 数据库 - Redis 缓存 - Nginx 反向代理、负载均衡 - Dubbo 服务发布和管理 - Zookeeper 服务注册中心 - Freemarker 页面静态化模板引擎 - FastDFS 图片服务器 - ...

    一个简洁的java http框架.rar

    支持文件上传和下载 支持灵活的模板表达式 支持拦截器处理请求的各个生命周期 支持自定义注解 支持OAuth2验证 支持过滤器来过滤传入的数据 基于注解、配置化的方式定义Http请求 支持Spring和Springboot集成 JSON格式...

    JAVA上百实例源码以及开源项目源代码

    2个目标文件,FTP的目标是:(1)提高文件的共享性(计算机程序和/或数据),(2)鼓励间接地(通过程序)使用远程计算机,(3)保护用户因主机之间的文件存储系统导致的变化,(4)为了可靠和高效地传输,虽然用户...

    t淘淘商城项目 商城项目 视频和源码教程 详细

    -- 文件上传组件 --&gt; &lt;groupId&gt;commons-fileupload &lt;artifactId&gt;commons-fileupload ${commons-fileupload.version} &lt;!-- Redis客户端 --&gt; &lt;groupId&gt;redis.clients &lt;artifactId&gt;jedis ${...

Global site tag (gtag.js) - Google Analytics