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. Java求一个数组中的最大值和最小值

    原创作品,转载请注明出处:https://www.cnblogs.com/sunshine5683/p/9927186.html 今天在工作中遇到对一个已知的一维数组取出其最大值和最小值,分别用于参与 ...

  2. [LeetCode]3Sum Closest题解

    3sum Closest: Given an array S of n integers, find three integers in S such that the sum is closest ...

  3. python单继沿用父类属性的两种方法

    方法一 在子类中用父类调用其init方法(不建议) 方法二 在子类中使用super获得父类的方法 class Aaimal(object): type_name = '动物类' def __init_ ...

  4. sql:PostgreSQL9.3 Using RETURNS TABLE vs. OUT parameters

    http://www.postgresonline.com/journal/archives/201-Using-RETURNS-TABLE-vs.-OUT-parameters.html http: ...

  5. [APIO2018] Circle selection 选圆圈(假题解)

    题面 自己去\(LOJ\)上找 Sol 直接排序然后\(KDTree\)查询 然后发现\(TLE\)了 然后把点旋转一下,就过了.. # include <bits/stdc++.h> # ...

  6. 关于电脑宽带显示连接 qq可以登录 但是无法上网的问题

    ---恢复内容开始--- 大家都遇到过这种情况吧,右下角显示网络已连接,但就是上不了网,解决的办法大都是什么,打开网络与共享中心设置什么协议什么的,当然,这些有可能是有用的,但是有一些不管怎么设置协议 ...

  7. C#-创建并添加TXT文件

    public static void WriteToText(string txtContent, string txtPath) { using (FileStream fs = new FileS ...

  8. GPU 编程语言 Harlan

    Harlan 是一个声明式的.GPU 领域特定的编程语言.目前主要是用于技术实现和优化的测试用途.该语言很小,用于简化浏览新的分析器和优化. 支持的操作系统: Mac OS X 10.6 (Snow ...

  9. flask多线程多协程操作

    local的作用:各个线程各开辟一块空间互不影响 基于local""" import threading from threading import local impo ...

  10. Mycat中间件

    数据库中间件Mycat自我介绍 一.mycat概述 1.功能介绍 mycat一个开源的分布式数据库系统,是一个实现了mysql协议的server前端用户可以把它看成一个数据库代理,用mysql客户端工 ...