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. [LeetCode] Binary Tree Postorder题解

    Binary Tree Postorder Given a binary tree, return the postorder traversal of its nodes' values. For ...

  2. InfluxDB 的卸载与重装

    我是通过下面方式安装的,所以卸载也是用的 rpm 的卸载命令 wget http://s3.amazonaws.com/influxdb/influxdb-latest-1.x86_64.rpm su ...

  3. 中小型研发团队架构实践三:微服务架构(MSA)

    一.MSA 简介 1.1.MSA 是什么 微服务架构 MSA 是 Microservice Architect 的简称,它是一种架构模式,它提倡将单一应用程序划分成一组小的服务,服务之间互相通讯.互相 ...

  4. JDK的安装与卸载

      1.jdk 下载链接:http://www.oracle.com/technetwork/java/javase/downloads/jdk9-downloads-3848520.html 2.在 ...

  5. spring boot包扫描不到controller层

    启动类代码 package com.maven.demo; import org.mybatis.spring.annotation.MapperScan; import org.springfram ...

  6. h5的classList对象

    H5新增属性classList h5中新增了一个classList,原生js可以通过它来判断获取dom节点有无某个class. classList是html元素对象的成员,它的使用非常简单,比如 co ...

  7. 如何用Fireworks制作经典的扫光字GIF动画

    1.首先我们把背景选为黑色.再输入文字用白色填充,注意调整文字之间的间隔. 2.选中字体,对其进行转换为路径文件. 3.对间隔再做少许调整. 4.复制文字改为黑色,做平移,出现立体效果. 5.再复制一 ...

  8. 使用 npm 安装 Vue

    使用 npm 安装 Vue 需要 node.js 就不多说了(从 nodejs.org 中下载 nodejs ) (1)安装 Vue,在 cmd 里直接输入: npm install -g cnpm ...

  9. Intent和BroadcastReceiver

    Intent简介 Intent是一种消息传递机制,作用: 使用类名显示启动一个特定的Service或Activity 启动Activity或Service来执行一个Intent 广播某个事件已经发生 ...

  10. 路飞学城知识点3缓存知识点之一Djang自带的缓存

    缓存是暂时把数据放到哪儿的意思,用于提高查询的访问速度用的,mysql等关系型数据库通常用作备份,数据库进行增删改操作一段时间内存同步到缓存(非关系型数据库中) 缓存与内存的区别: 通常把数据放到内存 ...