Java java httpclient4.5 进行http,https通过SSL安全验证跳过,封装接口请求 get,post(formdata,json)封装,文件上传下载
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)封装,文件上传下载的更多相关文章
- Java实现FTP批量大文件上传下载篇1
本文介绍了在Java中,如何使用Java现有的可用的库来编写FTP客户端代码,并开发成Applet控件,做成基于Web的批量.大文件的上传下载控件.文章在比较了一系列FTP客户库的基础上,就其中一个比 ...
- java实现文件上传下载
喜欢的朋友可以关注下,粉丝也缺. 今天发现已经有很久没有给大家分享一篇技术文章了,于是想了一下给大家分享一篇java实现文件上传下载功能的文章,不喜欢的希望大家勿喷. 想必大家都知道文件的上传前端页面 ...
- Java 客户端操作 FastDFS 实现文件上传下载替换删除
FastDFS 的作者余庆先生已经为我们开发好了 Java 对应的 SDK.这里需要解释一下:作者余庆并没有及时更新最新的 Java SDK 至 Maven 中央仓库,目前中央仓库最新版仍旧是 1.2 ...
- JAVA Web 之 struts2文件上传下载演示(二)(转)
JAVA Web 之 struts2文件上传下载演示(二) 一.文件上传演示 详细查看本人的另一篇博客 http://titanseason.iteye.com/blog/1489397 二.文件下载 ...
- JAVA Web 之 struts2文件上传下载演示(一)(转)
JAVA Web 之 struts2文件上传下载演示(一) 一.文件上传演示 1.需要的jar包 大多数的jar包都是struts里面的,大家把jar包直接复制到WebContent/WEB-INF/ ...
- java web 文件上传下载
文件上传下载案例: 首先是此案例工程的目录结构:
- 2013第38周日Java文件上传下载收集思考
2013第38周日Java文件上传&下载收集思考 感觉文件上传及下载操作很常用,之前简单搜集过一些东西,没有及时学习总结,现在基本没啥印象了,今天就再次学习下,记录下自己目前知识背景下对该类问 ...
- Java Web使用Html5 FormData实现多文件上传
前一阵子,迭代一个线上的项目,其中有一个图片上传的功能,之前用的ajaxfileupload.js来实现上传的,不过由于ajaxfileupload.js,默认是单文件上传(虽然可以通过修改源码的方法 ...
- CentOS下安装配置NFS并通过Java进行文件上传下载
1:安装NFS (1)安装 yum install nfs-utils rpcbind (2)启动rpcbind服务 systemctl restart rpcbind.service 查看服务状态 ...
随机推荐
- centos 安装cloud foundry CLI
步骤: 1.wget -O /etc/yum.repos.d/cloudfoundry-cli.repo https://packages.cloudfoundry.org/fedora/cloudf ...
- C# 后台处理图片的几种方式
第一种: 将上传图片直接保存到本地 var supportedTypes = new[] { "jpg", "jpeg", "png", & ...
- data-id 和 id 的区别
作者:Zeropoint零点 来源:CSDN 原文:https://blog.csdn.net/qq_41648132/article/details/80364335 版权声明:本文为Zeropoi ...
- html和css入门 (一)
HTML简介 什么是HTML HTML 的全称为 超文本标记语言(Hyper Text Markup Language),这种语言给我们提供一种建立结构性文档的方法.通过表示结构性的标签语法,我们可以 ...
- jsp页面乱码
- laravel开发之-安装laravel-admin
1.输入命令:composer require encore/laravel-admin "1.4.*" 2.在config/app.php中添加 :Encore\Admin\Pr ...
- Breakpoint debugging
断点调试的作用: A:查看程序的执行流程. B:调试程序. package basic.java; public class DebugTest { public static void main(S ...
- ButterKnife 初体验
ButterKnife 环境搭建 在project的build.gradle文件中添加依赖的插件 //ButterKnife 的插件 // classpath 'com.jakewharton:but ...
- [译] Z-variant (Z变体)
阅读目录 1. Z轴上的区别 2. 问题 Unihan 的 kZVariant 字段 译自: en.wikipedia.org/wiki/Z-variant | 已发布zh.wiki 在Unicode ...
- linux安装redis+RedisDesktopManager
一:redis简介 (REmote DIctionary Server Redis远程字典服务器) 1:Redis是一个开源的使用ANSI C语言编写.完全免费开源的,遵守BSD协议.支持 ...