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生成证书来 ...
随机推荐
- 基础知识 - Rabin-Karp 算法
Rabin-Karp 算法(字符串快速查找) Go 语言的 strings 包(strings.go)中用到了 Rabin-Karp 算法.Rabin-Karp 算法是基于这样的思路:即把字符串看作是 ...
- javascript类,对象,实例
在JS中,创建对象(Create Object)并不完全是我们时常说的创建类对象,JS中的对象强调的是一种复合类型一.由一对大括号括起来var emptyObj = {}; var myObj = { ...
- struts开发经验汇总
笔者接触struts2之时,对于web开发甚至还没有概念,仅有的知识是如何利用HTML.CSS和简单的JS进行静态网页的编写.对于开发一个网站所必需的后台.数据库基本没有了解. 因此这篇博文,可以说不 ...
- Qt 显示透明flash和编写QtWebkit插件
Qt 有两种方法可以显示flash. 1. 通过QAxWidget 调用com形式显示flash, 需要本机安装IE flash插件 2. 直接通过qwebview显示flash, 需要下载webki ...
- 防火墙导致FTP传输文件为0
在使用 ftpClient 传输文件到FTPserver时,在别的机器上可以正常使用,但是到自己的机器有就始终是0文件,发现是Mcafee 防火墙导致的,只要让防火墙放行即可. Mcafee防火墙的放 ...
- Android(java)学习笔记115:Android InputMethodManager输入法简介
正文 一.结构 public final class InputMethodManager extends Object Java.lang.Object android.view.inputmeth ...
- Emacs安装auto-complete
分别下载各个el文件 auto-complete-mode 主源码库 https://github.com/auto-complete/auto-complete 把zip文件下载后,复制auto-c ...
- DataTable 的数据导出到 Excel
如果有个DataTable类型的数据,可以这样导出到Excel中: public static void ExportToExcel(DataTable dt, string fileName) { ...
- c编写程序完成m名旅客和n辆汽车的同步程序代写
jurassic公园有一个恐龙博物馆和一个公园,有m名旅客和n辆汽车,每辆汽车仅能允许承载一名旅客.旅客在博物馆参观一阵,然后排队乘坐旅行车.当一辆车可用时,他载入一名旅客,再绕花园行驶任意长的时间. ...
- JDBC的批量查询报告内存溢出解决方法
由于表中的数据过多(我的超过了50W+),查询select * from table ....报告内存溢出 Exception in thread "main" java.lang ...