package api;

import java.util.*;
import java.net.URI;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import com.sun.org.apache.xml.internal.resolver.helpers.PublicId;
import com.sun.xml.internal.stream.Entity; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import java.io.*;
import java.io.File;
import org.apache.http.entity.mime.MultipartEntityBuilder; public class TestHttpClient {
static HttpPost post;
static HttpResponse response;
static HttpGet get;
static HttpEntity entity;
// private static Logger logger = Logger.getLogger(TestHttpClient.class); //ssl安全跳过
public static CloseableHttpClient getignoreSSLClient() {
CloseableHttpClient client =null;
try {
SSLContext sslContext=SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { @Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
client=HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); }catch(Exception e) {
e.printStackTrace();
}
return client;
} //
public static String getrequest(String url,Map<Object, Object> parameters,Map<Object,Object> headers){
String basicUrl=url;
String result=null;
String urlencoded=null;
// CloseableHttpClient httpclient=HttpClients.createDefault();
CloseableHttpClient httpclient=getignoreSSLClient();
List<NameValuePair> formData=new ArrayList<NameValuePair>(); try {
//参数分离
if(!url.contains("=")) {
if(parameters !=null && parameters.size()>0) {
for(Map.Entry<Object,Object> entry:parameters.entrySet()) {
String k =entry.getKey().toString();
String v=entry.getValue().toString();
formData.add(new BasicNameValuePair(k, v));
}
}
urlencoded =EntityUtils.toString(new UrlEncodedFormEntity(formData, Consts.UTF_8));
if(basicUrl.contains("?")) { get=new HttpGet(basicUrl+urlencoded);
if(headers !=null && headers.size()>0) {
for(Map.Entry<Object, Object> entry:headers.entrySet()) {
get.setHeader(entry.getKey().toString(),entry.getValue().toString());
}
}else {
get.setHeader(null);
}
response=httpclient.execute(get);
entity=response.getEntity();
result=EntityUtils.toString(entity,"UTF-8");
return result;
}else {
//无?
get=new HttpGet(basicUrl+"?"+urlencoded);
if(headers !=null && headers.size()>0) {
for(Map.Entry<Object, Object> entry:headers.entrySet()) {
get.setHeader(entry.getKey().toString(),entry.getValue().toString());
}
}else {
get.setHeader(null);
}
response=httpclient.execute(get);
entity=response.getEntity();
result=EntityUtils.toString(entity,"UTF-8");
return result;
}
}else { //纯url
get=new HttpGet(basicUrl);
response=httpclient.execute(get);
entity=response.getEntity();
result=EntityUtils.toString(entity,"UTF-8");
return result;
}
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(httpclient!=null) {
httpclient.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
return result;
} //postformData
public static String postformData(String url,Map<Object, Object> body,Map<Object, Object> headers){
String basicUrl=url;
String result=null; CloseableHttpClient httpclient=getignoreSSLClient();
List<NameValuePair> formData=new ArrayList<NameValuePair>();
try {
post =new HttpPost();
post.setURI(new URI(basicUrl));
//上面可以直接用post = new HttpPost(url)代替
for (Iterator iter = body.keySet().iterator(); iter.hasNext();) {
String k = (String) iter.next();
String v = String.valueOf(body.get(k));
formData.add(new BasicNameValuePair(k, v));
System.out.println("构造参数完毕");
}
if(headers !=null && headers.size()>0) {
for(Map.Entry<Object, Object> entry:headers.entrySet()) {
post.setHeader(entry.getKey().toString(),entry.getValue().toString());
}
}else {
post.setHeader(null);
//header设置完毕
}
post.setEntity(new UrlEncodedFormEntity(formData,Consts.UTF_8));
response = httpclient.execute(post);
entity =response.getEntity();
result=EntityUtils.toString(entity, "UTF-8");
int errorCode= response.getStatusLine().getStatusCode();
if(String.valueOf(errorCode)!=null) {
return result;
}else {
result=null;
return result;
} }catch(Exception e ) {
e.printStackTrace();
}finally {
try {
if(httpclient!=null) {
httpclient.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
return result;
} // postJson
public static String postJsonrequest(String url , Map<Object, Object> body , Map<Object, Object> headers){ String basicUrl=url;
String result=null;
post =new HttpPost(basicUrl);
CloseableHttpClient httpclient=getignoreSSLClient();
try {
if(headers !=null && headers.size()>0) {
for(Map.Entry<Object, Object> entry:headers.entrySet()) {
post.setHeader(entry.getKey().toString(),entry.getValue().toString());
}
}else {
post.setHeader(null);
//header设置完毕
}
//body转string,处理entity传入httpEntity
StringEntity newEntity=new StringEntity(body.toString(),"utf-8");
post.setEntity(newEntity);;
response=httpclient.execute(post);
int errorCode =response.getStatusLine().getStatusCode();
if(String.valueOf(errorCode) !=null) {
entity =response.getEntity();
result=EntityUtils.toString(entity, "UTF-8");
return result;
}
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(httpclient!=null) {
httpclient.close();
} }catch (Exception e) {
e.printStackTrace();
}
}
return result;
} // download file ,两个都要带路径
public static void downloadfile(String url,String localfileName,String remotefileName) {
FileOutputStream output = null;
InputStream in = null;
CloseableHttpClient httpclient=getignoreSSLClient();
try {
get=new HttpGet(url);
get.addHeader("fileName",remotefileName );
response=httpclient.execute(get);
entity =response.getEntity();
in = entity.getContent();
long length = entity.getContentLength();
if (length <= 0) {
return;
}
File localfile = new File(localfileName); if(! localfile.exists()) {
localfile.createNewFile();
}
output=new FileOutputStream(localfile);
byte[] buffer = new byte[4096];
int readLength = 0;
while ((readLength=in.read(buffer)) > 0) {
byte[] bytes = new byte[readLength];
System.arraycopy(buffer, 0, bytes, 0, readLength);
output.write(bytes);
}
output.flush();
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(in !=null) {
in.close();
}
if(output !=null) {
output.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
} // uploadfile
public static void uploadfile(String localfilepath,String url) { CloseableHttpClient httpclient=getignoreSSLClient();
try {
post = new HttpPost(url);
FileBody bin=new FileBody(new File(localfilepath));
HttpEntity reentity= MultipartEntityBuilder.create().addPart("bin",bin).build();
post.setEntity(entity);
response=httpclient.execute(post);
entity=response.getEntity();
if(entity!=null) {
// length entity.getContentLength();
String content=EntityUtils.toString(entity,"utf-8");
EntityUtils.consume(entity);
} }catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(httpclient!=null ) {
httpclient.close();
}
}catch(Exception e) {
e.printStackTrace();
}
} } }

  

Java java httpclient4.5 进行http,https通过SSL安全验证跳过,封装接口请求 get,post(formdata,json)封装,文件上传下载的更多相关文章

  1. Java实现FTP批量大文件上传下载篇1

    本文介绍了在Java中,如何使用Java现有的可用的库来编写FTP客户端代码,并开发成Applet控件,做成基于Web的批量.大文件的上传下载控件.文章在比较了一系列FTP客户库的基础上,就其中一个比 ...

  2. java实现文件上传下载

    喜欢的朋友可以关注下,粉丝也缺. 今天发现已经有很久没有给大家分享一篇技术文章了,于是想了一下给大家分享一篇java实现文件上传下载功能的文章,不喜欢的希望大家勿喷. 想必大家都知道文件的上传前端页面 ...

  3. Java 客户端操作 FastDFS 实现文件上传下载替换删除

    FastDFS 的作者余庆先生已经为我们开发好了 Java 对应的 SDK.这里需要解释一下:作者余庆并没有及时更新最新的 Java SDK 至 Maven 中央仓库,目前中央仓库最新版仍旧是 1.2 ...

  4. JAVA Web 之 struts2文件上传下载演示(二)(转)

    JAVA Web 之 struts2文件上传下载演示(二) 一.文件上传演示 详细查看本人的另一篇博客 http://titanseason.iteye.com/blog/1489397 二.文件下载 ...

  5. JAVA Web 之 struts2文件上传下载演示(一)(转)

    JAVA Web 之 struts2文件上传下载演示(一) 一.文件上传演示 1.需要的jar包 大多数的jar包都是struts里面的,大家把jar包直接复制到WebContent/WEB-INF/ ...

  6. java web 文件上传下载

    文件上传下载案例: 首先是此案例工程的目录结构:

  7. 2013第38周日Java文件上传下载收集思考

    2013第38周日Java文件上传&下载收集思考 感觉文件上传及下载操作很常用,之前简单搜集过一些东西,没有及时学习总结,现在基本没啥印象了,今天就再次学习下,记录下自己目前知识背景下对该类问 ...

  8. Java Web使用Html5 FormData实现多文件上传

    前一阵子,迭代一个线上的项目,其中有一个图片上传的功能,之前用的ajaxfileupload.js来实现上传的,不过由于ajaxfileupload.js,默认是单文件上传(虽然可以通过修改源码的方法 ...

  9. CentOS下安装配置NFS并通过Java进行文件上传下载

    1:安装NFS (1)安装 yum install nfs-utils rpcbind (2)启动rpcbind服务 systemctl restart rpcbind.service 查看服务状态 ...

随机推荐

  1. EMC光纤交换机故障处理和命令分析

        主机没有Login到存储是一个比较常见的故障,故障多发于主机新上线,或者是重启后.例如在Unisphere中,显示Host状态是”Registered: Yes; Logged In: No” ...

  2. hdu2044 一只小蜜蜂

    和之前的楼梯题一样,递推求解 但是要注意这里可以到50,结果已经超出了Int的范围,所以要用64位保存 #include<iostream> #include<cmath> # ...

  3. java设计模式-----9、观察者模式

    Observer模式是行为模式之一,它的作用是当一个对象的状态发生变化时,能够自动通知其他关联对象,自动刷新对象状态. Observer模式提供给关联对象一种同步通信的手段,使某个对象与依赖它的其他对 ...

  4. stm32f10x单片机进阶--spi使用

      使用SPI与外部flash(MX25L6406EM21)IC通信 连接方式                    如上图所示,MCU通过SPI2与外部flash芯片进行相连接. MCU spi2初 ...

  5. Angular入门教程一

    1 前言 前端技术的发展是如此之快,各种优秀技术.优秀框架的出现简直让人目不暇接,紧跟时代潮流,学习掌握新知识自然是不敢怠慢. AngularJS是google在维护,其在国外已经十分火热,可是国内的 ...

  6. System Test GIS压力测试利器

    System Test是ESRI公司提供一个压力测试软件.能针对ArcGIS Server 地图服务.WMS服务.WFS服务.WCS服务接口进行压力测试.以下是一个针对ArcGIS Server 地图 ...

  7. winform基础控件总结

    转自:http://www.cnblogs.com/top5/archive/2010/04/29/1724039.html 基础 - 常用控件 C# WinForm开发系列 - CheckBox/B ...

  8. eclipse 乱码问题总结

    Eclipse 的控制台必须用GBK编码.所以条件1和条件4必须同时满足否则运行的还是乱码.才能保证不是乱码. 条件1,Window  | Preferences  | Workspace  |  T ...

  9. oracle decode函数和 sign函数

    流程控制函数 DECODE decode()函数简介: 主要作用: 将查询结果翻译成其他值(即以其他形式表现出来,以下举例说明): 使用方法: Select decode(columnname,值1, ...

  10. Python初学者第十七天 函数(1)

    17day 函数 1.函数定义: 函数 是指将一组语句的集合通过一个名字(函数名)封装起来,想要执行这个函数,只需调用其函数名即可 2.函数的特性: a 减少重复代码 b 使程序变得可扩展 c 使程序 ...