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连接,传输数据文件的更多相关文章

  1. https连接的前几毫秒发生了什么

    在讨论这个话题之前,先提几个问题: 为什么说https是安全的,安全在哪里? https是使用了证书保证它的安全的么? 为什么证书需要购买? 我们先来看https要解决什么问题 (手机读者推荐移步ht ...

  2. java ssl https 连接详解 生成证书 tomcat keystone

    java ssl https 连接详解 生成证书 我们先来了解一下什么理HTTPS 1. HTTPS概念 1)简介 HTTPS(全称:Hypertext Transfer Protocol over ...

  3. ***Xcode Interface Builder或Storyboard中可建立那两种连接?

    在Xcode Interface Builder或Storyboard中,可建立到输出口(IBOutlet)和操作(方法,IBAction)的连接. IBOutlet are for output C ...

  4. 持久化API(JPA)系列(三)实体Bean的开发技术-建立与数据库的连接

    在EJB 2.x中.EJB有3种类型的Bean.各自是会话Bean(Session Bean).消息驱动Bean(Message-Driven Bean)和实体Bean(Entity Bean). 随 ...

  5. JRockit Mission Control建立到Tomcat的连接(windows)

    http://www.360doc.com/content/10/0928/16/203871_57086538.shtml  蓝海豹 JRockit Mission Control建立到Tomcat ...

  6. file_get_contents无法请求https连接的解决方法 php开启curl

    file_get_contents无法请求https连接的解决方法 方法1: PHP.ini默认配置下,用file_get_contents读取https的链接,就会如下错误: Warning: fo ...

  7. 记Outlook插件与Web页面交互的各种坑 (含c# HttpWebRequest 连接https 的完美解决方法)

    1) 方案一,  使用Web Service  基础功能没问题, 只是在连接https (ssh) 网站时, 需要针对https进行开发 (即http 和https 生成两套接口, 不太容易统一 ). ...

  8. CAS环境搭建-证书方式(https连接)

    一.教程前言 1 教程目的:从头到尾细细道来单点登录服务器及客户端应用的每个步骤 2 单点登录(SSO):请看<CAS简介> 3 本教程使用的SSO服务器是Yelu大学研发的CAS(Cen ...

  9. 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 ...

  10. tomcat7.0.55配置单向和双向HTTPS连接(二)

    上一篇文章:tomcat7.0.55配置单向和双向HTTPS连接 只是简要的配置了一下HTTPS,还有许多问题没有解决,本篇来解决这些文件 首先按照这篇文章:Widows下利用OpenSSL生成证书来 ...

随机推荐

  1. HBase Error: connection object not serializable

    HBase Error: connection object not serializable 想在spark driver程序中连接HBase数据库,并将数据插入到HBase,但是在spark集群提 ...

  2. BootStrap2学习日记9---文本框的前缀和后缀

    先来看一段代码: <form method="" action=""> <div class="input-append input ...

  3. STL之heap

    STL的堆操作 STL里面的堆操作一般用到的只有4个:make_heap();.pop_heap();.push_heap();.sort_heap(); 他们的头文件函数是#include < ...

  4. PHP读书笔记(3)-常量

    什么是常量 什么是常量?常量可以理解为值不变的量 :或者是常量值被定义后,在脚本的其他任何地方都不可以被改变.手册上是这么定义PHP的常量:常量是一个简单值的标识符(名字).如同其名称所暗示的,在脚本 ...

  5. oracle 设置标识列自增

    设置reg_user表 userid为自增列    1.设置键   2.创建序列   3.创建触发器

  6. [未完成]关于DOM的总结

    这样有什么好处吗? 一但这些东西变成了节点对象,意味着每一个节点对象都会有很多属性和行为提供出来. 如果div是一个对象,那么就可以针对这个对象调用其中的一些方法,对div操作. 这个操作可以包括,比 ...

  7. Android 内存分析工具 MAT(Memory Analyzer Tool)

    如果使用DDMS确实发现了我们的程序中存在内存泄漏,那又如何定位到具体出现问题的代码片段,最终找到问题所在呢?如果从头到尾的分析代码逻辑,那肯定 会把人逼疯,特别是在维护别人写的代码的时候.这里介绍一 ...

  8. 如何评价微信小程序?

    这次我不站张小龙,虽然他说的「用完即走」的道理在,但我并不认为小程序会形成生态. (一) 仅仅从抽象场景上来讲,小程序当然很美好. 对开发者来说,不用费尽心思开发好多平台的 APP 了,不用考虑适配各 ...

  9. vsftp实现ftps加密传输数据

    FTP明文传输数据,不太安全,ftp+ssl可以实现传输加密=ftps 01.创建FTP用户 user -d /ftp_www  -s /sbin/nologin mvpbang echo " ...

  10. Lombok(1.14.8) - @Synchronized

    @Synchronized @Synchronized,实现同步. package com.huey.lombok; import java.util.Date; import lombok.Sync ...