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生成证书来 ...
随机推荐
- 小白日记14:kali渗透测试--NMAP
NAMP 被认为是最强大的扫描器 所有参数 root@kali:~# nmap Nmap 7.01 ( https://nmap.org ) Usage: nmap [Scan Type(s)] [O ...
- Window Pains
http://poj.org/problem?id=2585 Window Pains Time Limit: 1000MS Memory Limit: 65536K Total Submissi ...
- 实用JS大全
****************************************************************(一)常用元素,对象,事件,技巧 事件源对象 event.srcElem ...
- poj1068解题报告(模拟类)
POJ 1068,题目链接http://poj.org/problem?id=1068 题意: 对于给出给出的原括号串S,对应两种数字密码串P.W: S (((()()()))) P- ...
- Android进阶笔记12:Manymo(在线安卓系统模拟器工具)
Manymo: 在线安卓系统模拟器工具是一款启动速度快,且在浏览器中就能运行流畅.你可以使用它来测试你的安卓应用,他最多能支持42种屏幕尺寸和系统版本. 长久以来,Android开发者面临的困境之一就 ...
- iOS银行卡合法性校验
项目中用到了校验银行卡,就拿来贴上来了 + (BOOL)checkCardNo:(NSString*)cardNo;//判断银行卡 + (BOOL)checkCardNo:(NSString*)car ...
- 【转】istringstream、ostringstream、stringstream 类介绍 .
http://www.cnblogs.com/gamesky/archive/2013/01/09/2852356.html 好吧,懒死我算了
- 【memset】关于memset的初始最大最小值
声明:也是摘自网上各路大神的. memset的正规用法是只能用来初始化char类型的数组的,也就是说,它只接受0x00-0xFF的赋值. 因为char是1字节,memset是按照字节赋值的,相当于把每 ...
- Netty线程模型
一.Reactor模型 1.单线程模型 Reactor单线程模型,指的是所有的IO操作都在同一个NIO线程上面完成,NIO线程的职责如下: 1)作为NIO服务端,接收客户端的TCP连接: 2)作为NI ...
- Emmet 语法大全(缩写语法/sublime 插件)
Emmet 使用类似于 CSS 选择器的语法描述元素在生成的文档树中的位置及其属性. 元素 可以使用元素名(如 div 或者 p)来生成 HTML 标签.Emmet 没有预定义的有效元素名的集合,可以 ...