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 查看服务状态 ...
随机推荐
- java map常用的4种遍历方法
public static void main(String[] args) { Map<String, String> map = new HashMap<String, Stri ...
- sql:PostgreSQL9.3 Using RETURNS TABLE vs. OUT parameters
http://www.postgresonline.com/journal/archives/201-Using-RETURNS-TABLE-vs.-OUT-parameters.html http: ...
- 4.5&4.7联考题解
本来想加个密码的,后来一想全HE就咱们这几个人,外省的dalao愿看也没事儿,就公开算了,省得加密码各种麻烦. 先补这两天的题解吧……如果有空的话我可能会把上次联考的题解补上= =(中午没睡觉,现在困 ...
- 在linux中给你的应用做压力测试
在linux中给你的应用做压力测试 作者: 立地 邮箱: jarvin_g@126.com QQ: 511363759 一.webbench 1.在Ubuntu中安装webbench —支持get,h ...
- GDAL读取影像并插值
影像读取 并缩放 读取大影像某一部分,并缩放到指定大小,我们有时会用如下代码: #include "gdal.h" #include "gdal_priv.h" ...
- appium定位安装包启动类名称
cmd输入:adb logcat > d:/1.txt 然后运行APP,关闭APP,到D盘查找文件1,Ctrl+F,输入LAUNCHER,定位启动类,如下图所示位置 即为,eclipse调用A ...
- vue组件编写知识点
- java 简单工厂 工厂模式
<Head First 设计模式>学习中 分类 简单工厂模式(Simple Factory) 工厂方法模式(Factory Method) 抽象工厂模式(Abstract Factory) ...
- Castle.Windsor IOC/AOP的使用
Castle最早在2003年诞生于Apache Avalon项目,目的是为了创建一个IOC(控制反转)框架.发展到现在已经有4个组件了,分别是ActiveRecord(ORM组件).Windsor(I ...
- Python学习---Python的框架基础学习
框架基础 框架实质: 所有的Web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端 B/S结构的响应: import socket def handle_requ ...