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. 网络IPC:套接字之套接字选项

    套接字机制提供两个套接字选项接口来控制套接字的行为.一个接口用来设置选项,另一个接口允许查询一个选项的状态.可以获取或设置的三种选项: (1)通用选项,工作在所有套接字类型上. (2)在套接字层次管理 ...

  2. 关于try...catch...finally中return的疑惑

    原文:http://www.cnblogs.com/and_he/archive/2012/04/17/2453703.html 关于try...catch...finally里面的return一直是 ...

  3. SVN 修改URL路径

    http://strugglelinux.blog.51cto.com/1009905/672008 标签:休闲 SVN 修改URL路径 职场 原创作品,允许转载,转载时请务必以超链接形式标明文章 原 ...

  4. mkimage command not found

    转载:http://blog.csdn.net/armeasy/article/details/6217621 UIMAGE  arch/arm/boot/uImage"mkimage&qu ...

  5. iOS搜索框

    在iOS8以前搜索框是作为一个控件添加到TableViewController中, 有系统自带的搜索变量self.searchDisplayController 遵守一个搜索显示的协议<UISe ...

  6. LeetCode 231

    Power of Two Given an integer, write a function to determine if it is a power of two. /************* ...

  7. [改善Java代码]在switch的default代码块中增加AssertionError错误

    switch的后跟枚举类型,case后列出所有的枚举项,这是一个使用枚举的主流写法,那留着default语句似乎没有任何作用了,程序已经列举出了所有的可能选项,肯定不会执行到default语句,. 错 ...

  8. 自定义HBase的协处理器(Observer)

    自定义一个Observer... 总共分五步: 1°.继承BaseMasterObserver  (写代码  具体看博客....) 案例(当在HBase中创建表的时候在日志中有相关输出): impor ...

  9. 关于Eclipse的工作空间设置默认个数和配置

    &

  10. [ImportNew]8张图理解Java

    http://www.importnew.com/11725.html 1.字符串的不变性. 下面这张图展示了这段代码做了什么 String s = "abcd"; s = s.c ...