<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.relevantcodes</groupId>
<artifactId>extentreports</artifactId>
<version>2.41.1</version>
</dependency>
<dependency>
<groupId>com.vimalselvam</groupId>
<artifactId>testng-extentsreport</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>3.0.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.14</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
package zhihuisystem.HttpClient_Test;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils; public class HttpClient_Utils {
// 常规get请求
public static String Getmethod(String url) {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(url);
CloseableHttpResponse respons1 = null;
try {
respons1 = client.execute(get);
} catch (ClientProtocolException e1) {
System.out.println("客户端get请求异常");
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 切割字符串
String result = respons1.getStatusLine().toString().split(" ")[1]; try {
client.close();// 释放资源
} catch (IOException e) {
System.out.println("请求连接无法关闭,关注get方法!");
e.printStackTrace();
}
return result; } // 常规P0ST请求
public static String HttpPostWithJson(String url, String json) { String returnValue = "这是默认返回值,接口调用失败";
CloseableHttpClient httpClient = HttpClients.createDefault();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
// 创建HttpClient对象
httpClient = HttpClients.createDefault();
// 创建httpPost对象
HttpPost httpPost = new HttpPost(url);
// 给httpPost设置JSON格式的参数
StringEntity requestEntity = new StringEntity(json, "utf-8");
requestEntity.setContentEncoding("UTF-8");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(requestEntity);
// 发送HttpPost请求,获取返回值
returnValue = httpClient.execute(httpPost, responseHandler); // 调接口获取返回值,用此方法
} catch (Exception e) {
System.out.println("请求返回值为空!");
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
System.out.println("请求连接无法关闭,关注post方法!");
e.printStackTrace();
}
}
// 第五步:处理返回值
return returnValue;
} // 忽略证书的HTTPS请求 - get
public static String HttpsGetIgnoreCertification(String url)
throws NoSuchAlgorithmException, KeyManagementException, ClientProtocolException, IOException {
// First create a trust manager that won't care.
X509TrustManager trustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// Don't do anything.
} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// Don't do anything.
} public X509Certificate[] getAcceptedIssuers() {
// Don't do anything.
return null;
} };
// 现在将信任管理器放到SSLContext中。
SSLContext sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(null, new TrustManager[] { trustManager }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sf, 443)); HttpGet httpget = new HttpGet(url);
// String result = "";
httpget.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
// String result1 = response.getStatusLine().toString();
// String result2 = response.getStatusLine().toString().split(" ")[2];
String result3 = response.getStatusLine().toString().split(" ")[1];
return result3; } // 忽略证书的HTTPS请求 - post
public static String HttpsPostIgnoreCertification(String url, String requestData)
throws NoSuchAlgorithmException, KeyManagementException, ClientProtocolException, IOException {
// First create a trust manager that won't care.
X509TrustManager trustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// Don't do anything.
} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// Don't do anything.
} public X509Certificate[] getAcceptedIssuers() {
// Don't do anything.
return null;
} };
// 现在将信任管理器放到SSLContext中。
SSLContext sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(null, new TrustManager[] { trustManager }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sf, 443)); HttpPost httpPost = new HttpPost(url);
String result = "";
// httpPost.setHeader("Authorization", "basic " + "dGNsb3VkYWRtaW46dGNsb3VkMTIz");
httpPost.setHeader("Content-type", "application/json");
StringEntity reqEntity;
// 将请求参数封装成HttpEntity
reqEntity = new StringEntity(requestData);
BufferedHttpEntity bhe = new BufferedHttpEntity(reqEntity);
httpPost.setEntity(bhe); HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
InputStreamReader reader = new InputStreamReader(resEntity.getContent());
// 取内存资源
char[] buff = new char[1024];
int length = 0;
while ((length = reader.read(buff)) != -1) {
result += new String(buff, 0, length);
}
httpclient.close();
return result; // System.out.println(result);
} // 启用HTTPS携带证书GET请求
public static String HttpsforGet(String url, String keystore_PathFile, String keypwd) throws IOException,
KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException {
HttpGet httpGet = new HttpGet(url);
CloseableHttpClient httpClient = null;
if (url.startsWith("https")) {
// "E:\\White_testNG\\mock\\mock_https\\isa\\isa.keystor"
File cert = new File(keystore_PathFile);
String keystore = keypwd;
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(cert, keystore.toCharArray(), new TrustSelfSignedStrategy()).build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
null, NoopHostnameVerifier.INSTANCE);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
} else {
httpClient = HttpClients.createDefault();
}
try (CloseableHttpClient _httpClient = httpClient; CloseableHttpResponse res = _httpClient.execute(httpGet);) { StatusLine sl = res.getStatusLine();
// System.out.println(sl.toString().split(" ")[1]);
String result = sl.toString().split(" ")[1];
/*
* if (sl != null) { System.out.println(sl.getStatusCode()); StringBuilder
* builder = new StringBuilder(); try (InputStream is =
* res.getEntity().getContent(); InputStreamReader isr = new
* InputStreamReader(is); BufferedReader br = new BufferedReader(isr);) { String
* line = br.readLine(); while(line != null) { builder.append(line); line =
* br.readLine(); } System.out.println("响应结果:" + builder.toString());
*/
return result;
}
} // 启用HTTPS携带证书post请求
public static String HttpsforPost(String url, String keystore_PathFile, String keypwd, String json)
throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException,
KeyStoreException, CertificateException { String returnValue = "这是默认返回值,接口调用失败";
HttpPost httppost = new HttpPost(url);
CloseableHttpClient httpClient = null;
if (url.startsWith("https")) {
File cert = new File(keystore_PathFile);
String keystore = keypwd;
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(cert, keystore.toCharArray(), new TrustSelfSignedStrategy()).build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
null, NoopHostnameVerifier.INSTANCE);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
} else {
httpClient = HttpClients.createDefault();
}
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try (CloseableHttpClient _httpClient = httpClient; CloseableHttpResponse res = _httpClient.execute(httppost);) {
StringEntity requestEntity = new StringEntity(json, "utf-8");
requestEntity.setContentEncoding("UTF-8");
httppost.setHeader("Content-type", "application/json");
httppost.setEntity(requestEntity);
// 发送HttpPost请求,获取返回值
returnValue = httpClient.execute(httppost, responseHandler); // 调接口获取返回值,用此方法 // System.out.println(returnValue); }
return returnValue; } }

httpclient常规封装的方法的更多相关文章

  1. 完成OSS.Http底层HttpClient重构封装 支持标准库

    OSS.Http项目对于.Net Standard标准库的支持已经迁移完毕,OSS开源系列两个最底层的类库已经具备跨运行时支持的能力.由于OSS.Http类库是几年前我参照RestSharp的思路,完 ...

  2. HttpClient 常用方法封装

    简介 在平时写代码中,经常需要对接口进行访问,对于 http 协议 rest 风格的接口请求,大多使用 HttpClient 工具进行编写,想着方便就寻思着把一些常用的方法进行封装,便于平时快速的使用 ...

  3. js封装的方法

    1.JS封装就是尽量把使用的方式简单化,内部逻辑和使用解耦.通俗的说就是使用的时候只需要知道参数和返回值,其他条件尽量不要使用人员进行设置. 2.JS封装的方法有函数方式.对象的方式.闭包的方式. 举 ...

  4. Visual Studio快速封装字段方法

    在面向对象的编程中我们常常要将各个字段封装为属性,但是当字段多的时候往往这个重复的操作会大大降低我们的开发效率,那么如何才能快速的封装字段呢?下面就给大家2个解决方法: 1.使用封装字段方法: 选中字 ...

  5. 关于tween.js 封装的方法

    今天做的是匀速情况下div的运动.首先开始之前先了解运动的原理 A------------>>BA移动到B 这段距离是总距离 用一个变量保存下来:var dA移动到B 移动的总次数  用一 ...

  6. xml方式封装数据方法

    1.xml方式封装数据方法 2.demo <?php xml方式封装数据方法 /** * [xmlEncode description] * @param [type] $code [descr ...

  7. Kong管理UI -kong-dashboard (附kong封装webservice方法)

    本文仍然是在centos 6.7的环境下进行                 本文转载请注明出处 —— xiaoEight btw如果要正常使用管理UI,前提为kong已经正常run(可参考)起来,此 ...

  8. angular 封装公共方法

    angular封装公共方法到service中间件,节省开发时间 layer.service.ts openAlert(callback) {// 传递回调函数 const dialogRef = th ...

  9. jsonp跨域 封装通用方法

    jsonp跨域 封装通用方法 //用法如下 jsonp({ url:"https://www.xxxx.com", params:{wd:'b'}, callback:'show' ...

随机推荐

  1. SpringBoot之配置文件的注入

    @PropertySource&@ImportResource&@Bean @PropertySource:加载指定的配置文件: /** * 将配置文件中配置的每一个属性的值,映射到这 ...

  2. 设计模式C++描述----18.中介者(Mediator)模式

    一. 举例 比如,现在中图和日本在关于钓鱼岛问题上存在争端.这时,联合国就会站出来,做为调解者,其实也没什么好调解的,钓鱼岛本来就是中国的,这是不争的事实!联合国也就是个传话者.发言人. 结构图如下: ...

  3. mysql全局变量和局部变量

    全局变量和局部变量 在服务器启动时,会将每个全局变量初始化为其默认值(可以通过命令行或选项文件中指定的选项更改这些默认值).然后服务器还为每个连接的客户端维护一组会话变量,客户端的会话变量在连接时使用 ...

  4. Unity中的资源管理

    一.AssetBundle 相关 Q1:Unity中的SerializedFile是怎么产生的?请问用Unload(false)可以清除吗?因为读取了Bundle里面的内容后已经赋值给其他物体了.而且 ...

  5. 【JAVA】可视化计算器

    import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.Actio ...

  6. git 设置不用每次都输入 账号密码

    执行命令 git config --global credential.helper store 然后,下次再输入一次 账号密码 就可以了.

  7. GPIO硬件资源的申请,内核空间和用户空间的数据交换,ioctl(.....),设备文件的自动创建

    1.通过GPIO库函数控制LED   open("/dev/myleds",...)       close(fd)   ----------------------------- ...

  8. 文件输入输出函数fgetc/fputc及fgets/fputs等文件指针位置的变化

    文件打开后才可以对文件进行操作.也就是说,文件必须经历打开-操作-关闭的过程.如前所述,C语言对文件的操作都是通过调用标准I/O库函数来实现的.文件操作实际是指对文件的读写.文件的读操作就是从文件中读 ...

  9. maven编码配置

    在环境变量里添加变量 MAVEN_OPTS -Xms256m -Xmx512m -Dfile.encoding=UTF-8

  10. Apache Jmeter进行服务器压力测试

    1.前言 最近项目遇到一个问题:其他公司对接我们系统,请求量太大的时候,返回单给对方就是丢失格式,大概十几万中总有那么十几单会出现格式错误! 所以我们老大就叫我用apache jmeter来进行并发测 ...