HttpClient 建立http连接,https连接,传输数据文件
package com.bluedon.bsmon.http;
import java.io.File;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import javax.net.ssl.SSLContext; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileHttpClient { private static Logger log=LoggerFactory.getLogger(FileHttpClient.class);
private String url;
private ContentType contentType;
private static HttpClientBuilder httpclientbuilder;
private HttpClient httpclient;
private String RequestType;
static{
httpclientbuilder=HttpClientBuilder.create(); }
/**
*
* @param url http,支持代理服务器
* @param contentType MIME type 表单类型
* @param RequestType 请求类型post,get
* @return
*/
public static FileHttpClient createHttpClient(String url,ContentType contentType,String RequestType){
log.info("url:{}",url);
log.info("====初始化====");
FileHttpClient client=new FileHttpClient(); client.url=url;
if(contentType==null||contentType.equals(""))
{
contentType=ContentType.MULTIPART_FORM_DATA;
}
if(RequestType==null||RequestType.equals("post"))
{
RequestType="post";
}else{
RequestType="get";
}
contentType=contentType.withCharset(Charset.forName("UTF-8"));
client.contentType=contentType;
client.RequestType=RequestType;
return client; }
/**
* http请求初始化
*/
private void initHttp(){
this.httpclient=
httpclientbuilder.build();
}
/**
* ssl文件上传初始化
* 如果是ssl文件上传必须要调用这个方法
*/
private void ssLInit(){
log.info("====SSL请求====");
try {
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial( new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {//信任所有
return true;
}
}).build();
SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslcontext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
this.httpclient= HttpClients.custom().setSSLSocketFactory(sf).build(); } catch (Exception e) { e.printStackTrace();
}
}
/**
* 设置需要传输的参数
* @param params
*/
private MultipartEntityBuilder SetForm(Map<Object,Object> params){
MultipartEntityBuilder MultipartBuilder=MultipartEntityBuilder.create();
if(params==null)return MultipartBuilder;
Iterator<Object> it=params.keySet().iterator();
while(it.hasNext()){
Object key=it.next();
Object item=params.get(key);
if(item instanceof File){
log.info("单个文件");
File file=(File) item;
FileBody filebody=new FileBody(file, contentType);
MultipartBuilder.addPart(key+"", filebody);
}
else if(item instanceof List){
log.info("多个文件");
for(Object obj:(List)item)
{ if(obj instanceof File){
File file=(File) obj;
FileBody filebody=new FileBody(file);
MultipartBuilder.addPart(key+"", filebody);
}else{
ContentBody comment = new StringBody(obj+"",contentType);
MultipartBuilder.addPart(key+"",comment);
} } }
else{ ContentBody comment = new StringBody(item+"",contentType);
MultipartBuilder.addPart(key+"",comment);
} }
return MultipartBuilder;
}
/**
* 运行,先调用createHttpClient方法
* @return
*/ private String requestRun(MultipartEntityBuilder MultipartBuilder){ HttpPost httppost = new HttpPost(url);
httppost.addHeader( "Connection", "close"); HttpEntity reqEntity=MultipartBuilder.build(); httppost.setEntity(reqEntity);
HttpResponse response = null;
try { response = this.httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
String responseText="";
if(statusCode == HttpStatus.SC_OK){
System.out.println("服务器正常响应.....");
HttpEntity resEntity = response.getEntity();
responseText=EntityUtils.toString(resEntity);
log.info(responseText);//httpclient自带的工具类读取返回数据 EntityUtils.consume(resEntity);
log.error("接收到信息:{}",responseText);
return responseText;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}finally{
httppost.releaseConnection(); }
return null; }
/**
* 表单提交,支持http,https
* @param url 请求的连接
* @param contentType 内容类型
* @param formParams 表单参数,如果是文件
* @return
*/
public String formSubmit(Map<Object,Object> formParams){
if(contentType==null)contentType=ContentType.MULTIPART_FORM_DATA; if(url.startsWith("https")){
this.ssLInit();
}else{
this.initHttp();
}
MultipartEntityBuilder MultipartBuilder= SetForm(formParams);
String result=requestRun(MultipartBuilder);
log.info("表单提交");
return result;
} public static void main(String[] args) {
FileHttpClient client=FileHttpClient.createHttpClient("https://172.16.2.185/BDMbsecsvr/filereceive/receive_data.do", ContentType.MULTIPART_FORM_DATA,"post");
client.ssLInit();
Map<Object, Object> params=new HashMap<Object, Object>();
File file=new File("E:\\7.png");
params.put("files", file);
params.put("paths", "upload/news_images/1452567879310060149.png"); MultipartEntityBuilder MultipartBuilder= client.SetForm(params);
String result=client.requestRun(MultipartBuilder);
System.out.println("输出===="+result);
}
}
HttpClient 建立http连接,https连接,传输数据文件的更多相关文章
- https连接的前几毫秒发生了什么
在讨论这个话题之前,先提几个问题: 为什么说https是安全的,安全在哪里? https是使用了证书保证它的安全的么? 为什么证书需要购买? 我们先来看https要解决什么问题 (手机读者推荐移步ht ...
- java ssl https 连接详解 生成证书 tomcat keystone
java ssl https 连接详解 生成证书 我们先来了解一下什么理HTTPS 1. HTTPS概念 1)简介 HTTPS(全称:Hypertext Transfer Protocol over ...
- ***Xcode Interface Builder或Storyboard中可建立那两种连接?
在Xcode Interface Builder或Storyboard中,可建立到输出口(IBOutlet)和操作(方法,IBAction)的连接. IBOutlet are for output C ...
- 持久化API(JPA)系列(三)实体Bean的开发技术-建立与数据库的连接
在EJB 2.x中.EJB有3种类型的Bean.各自是会话Bean(Session Bean).消息驱动Bean(Message-Driven Bean)和实体Bean(Entity Bean). 随 ...
- JRockit Mission Control建立到Tomcat的连接(windows)
http://www.360doc.com/content/10/0928/16/203871_57086538.shtml 蓝海豹 JRockit Mission Control建立到Tomcat ...
- file_get_contents无法请求https连接的解决方法 php开启curl
file_get_contents无法请求https连接的解决方法 方法1: PHP.ini默认配置下,用file_get_contents读取https的链接,就会如下错误: Warning: fo ...
- 记Outlook插件与Web页面交互的各种坑 (含c# HttpWebRequest 连接https 的完美解决方法)
1) 方案一, 使用Web Service 基础功能没问题, 只是在连接https (ssh) 网站时, 需要针对https进行开发 (即http 和https 生成两套接口, 不太容易统一 ). ...
- CAS环境搭建-证书方式(https连接)
一.教程前言 1 教程目的:从头到尾细细道来单点登录服务器及客户端应用的每个步骤 2 单点登录(SSO):请看<CAS简介> 3 本教程使用的SSO服务器是Yelu大学研发的CAS(Cen ...
- php soap连接https的wsdl报错SOAP-ERROR: Parsing WSDL:Couldn't load from
转发:https://blog.csdn.net/keyunq/article/details/51804728 SOAP-ERROR: Parsing WSDL:Couldn’t load from ...
- tomcat7.0.55配置单向和双向HTTPS连接(二)
上一篇文章:tomcat7.0.55配置单向和双向HTTPS连接 只是简要的配置了一下HTTPS,还有许多问题没有解决,本篇来解决这些文件 首先按照这篇文章:Widows下利用OpenSSL生成证书来 ...
随机推荐
- 用scikit-learn实现朴素贝叶斯分类器 转
原文:http://segmentfault.com/a/1190000002472791 朴素贝叶斯(Naive Bayes Classifier)是一种「天真」的算法(假定所有特征发生概率是独立的 ...
- 炼数成金hadoop视频干货04
视频地址:http://pan.baidu.com/s/1dDEgKwD 这一节讲的全是理论 任务执行优化 : 1.推测式执行: 2.重用JVM: 3.忽略模式. 除了手动修改Log4J.proper ...
- Spreadsheet Tracking
Spreadsheet Tracking Data in spreadsheets are stored in cells, which are organized in rows (r) and ...
- Windows主机通过SSH连接虚拟机里的Linux系统
Windows 7 + VMware 11 VMWare里:编辑-虚拟网络编辑器-VMnet8(NAT模式)-NAT设置...添加主机端口和虚拟机IP地址以及虚拟机端口 Windows7系统:wind ...
- [课程相关]homework-07
我读的博客: C++11中值得关注的几大变化 C++11 中的线程.锁和条件变量 C++开发者都应该使用的10个C++11特性 开始使用C++11的9个理由 我的问题: 1.有一句话:“C++像难懂的 ...
- linux 安装GCC
研究生阶段已经开始了一段时间了,选了LINUX深入分析,之前没怎么接触过,感觉还是有点难度的.不,好像是很难. 从学校借了一台电脑,安装了UBUNTU12.04的系统,可是不知道怎么地,这个系统里,没 ...
- poj 2104 划分树
思路:裸的划分树 #include<iostream> #include<algorithm> #include<cstring> #include<cstd ...
- Springmvc+uploadify实现文件带进度条批量上传
网上看了很多关于文件上传的帖子,众口不一,感觉有点乱,最近正好公司的项目里用到JQuery的uploadify控件做文件上传,所以整理下头绪,搞篇文档出来,供亲们分享. Uploadify控件的主要优 ...
- asp.net php asp jsp 301重定向的代码
介绍一下针对各类程序系统实施301重定向的代码: 1.Linux主机重定向 Godaddy的Liunx主机,Godaddy本身已经支持Apache,所以直接创建一个.htaccess文件就可以了,一般 ...
- Agile.Net 组件式开发平台 - 内核管理组件
敏捷开发体系 软件构件技术:所谓软件构件化,就是要让软件开发像机械制造工业一样,可以用各种标准和非标准的零件来进行组装.软件的构件化和集成技术的目标是:软件系统可以由不同厂商提供的,用不同语言开发 ...