package com.yinhang.jiekou;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.logging.Logger;
/**
* @author syx
* @create 2022-04-09 17:45
*/
public class TestRestAssured {
//============================此下面是okhttpclient==============================
@Test
@Parameters({"firstname","lastname"})
public void test1(String fn,String la){
System.out.println(fn+"......."+la);
}
@Test(dataProvider = "datas")
public void test2(String ffa,String lla){
System.out.println(ffa+"..."+lla);
}
@DataProvider(name = "datas")
public Object[][] datas(){
Object[][] datas= {
{"nigulasi", "zhaosi"},
{"亚历山大", "催化"}
};
return datas;
}
@Test(description = "get请求")
public void test3() throws IOException {
//1.创建okhttpclient请求
String yrl="https://www.baidu.com";
OkHttpClient client = new OkHttpClient();
//2.构建request
Request rquest = new Request.Builder()
.url(yrl)
.get()
.build();
//3.返回一个响应请求
Response response = client.newCall(rquest).execute();
System.out.println(response.code());
System.out.println("响应头"+response.headers());
System.out.println("响应体"+response.body().string());
}
@Test(description = "post请求")
public void test4() throws IOException {
String url="http://test.lemonban.com/ningmengban/mvc/user/login.json";
//创建okhttpclient
OkHttpClient clients = new OkHttpClient();
//构建request
MediaType type = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(type, "username=13212312312&password=123123");
Request build = new Request.Builder()
.url(url)
.post(body)
.build();
//返回一个响应信息
Response response1 = clients.newCall(build).execute();
System.out.println(response1.code());
System.out.println(response1.headers());
System.out.println(response1.body().string());
}
/*================================此下面是httpclient====================================
* 使用jdk原生的api来请求网页
*/
@Test
public void test5() throws IOException {
String url2="https://www.baidu.com";
URL url3 = new URL(url2);
//使用url3对象打开一个openConnection连接
URLConnection urlConnection = url3.openConnection();
//将连接强转
HttpURLConnection httpURLConnection= (HttpURLConnection) urlConnection;
//设置请求类型
/*
请求信息组成
请求行
空格
请求头
请求体
* */
httpURLConnection.setRequestMethod("GET");
//可以设置请求头之类的属性
httpURLConnection.setRequestProperty("Accept-Charset","utf-8");
//获取httpurlConnection输入流
try (
InputStream is=httpURLConnection.getInputStream();
InputStreamReader isr=new InputStreamReader(is,"UTF-8");
BufferedReader br = new BufferedReader(isr);
){
String line;
while ((line=br.readLine()) != null){
System.out.println(line);
}
}
}
//通过httpclient发送get无参请求
@Test(description = "通过httpclient发送get无参请求")
public void test6() throws IOException {
//设置一个可关闭的httpclient客户端,相当于你打开一个浏览器
CloseableHttpClient aDefault = HttpClients.createDefault();
//指定一个url4
String url4="https://www.baidu.com";
//构建httpget请求对象
HttpGet httpGet = new HttpGet(url4);
//=====================位置在Network-Fetch/XHR-headers========================
/*除了User-Agent,Referer,还可以用httpget.addheader添加请求头等等*/
//解决httpclient被认为不是真人行为
httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36");
//防盗链,value:发生防盗链的网站的url,例如:解决图片爬不下来
httpGet.addHeader("Referer","https://www.baidu.com/");
//=============================================
//创建一个可关闭的响应对象CloseableHttpResponse
CloseableHttpResponse response=null;
try {
response = aDefault.execute(httpGet);
//获取响应结果
/*
HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多的实现
*/
HttpEntity entity = response.getEntity();
//对HttpEntity操作的工具类EntityUtils,输出一下内容
String entitystring = EntityUtils.toString(entity,"utf-8");
System.out.println(entitystring);
//确保流关闭
EntityUtils.consume(entity);
}catch (Exception e){
e.printStackTrace();
}finally {
//关闭 可关闭的httpclient客户端
if (aDefault != null){
try {
aDefault.close();
}catch (IOException e){
e.printStackTrace();
}
}
//关闭 可关闭的响应对象CloseableHttpResponse
if (response != null){
try {
response.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
/*get有参请求URLEncode*/
@Test(description = "请求邮箱接口需要重新学习")
public void test7() throws UnsupportedEncodingException {
//创建一个可关闭的httpclient客户端,如浏览器
CloseableHttpClient closeableHttpClient=HttpClients.createDefault();
//创建一个url路径
//String passwordStr="xxxxxxxx";
//passwordStr=URLEncoder.encode(passwordStr,"UTF-8");//给字段转成utf-8
//https://mail.163.com/contacts/call.do?uid=xxxxxxxx&sid=xxxxxxxxZvlkLiwm&from=webmail&cmd=newapi.getContacts&vcardver=3.0&ctype=all&attachinfos=yellowpage,frequentContacts&freContLim=20
String url="https://mail.163.com/contacts/call.do?uid=xxxxxxxx&sid=xxxxxxxx&ctype=all&attachinfos=yellowpage,frequentContacts&freContLim=20";
//
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36");
httpGet.addHeader("referer","https://mail.163.com/js6/main.jsp?sid=VAjJlaRRpymbkNjTrmRRqMvDZvlkLiwm&df=mail163_letter");
CloseableHttpResponse response=null;
try {
response= closeableHttpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String s = EntityUtils.toString(entity);
System.out.println(s);
}catch (Exception e){
e.printStackTrace();
}finally {
if (closeableHttpClient != null){
try {
closeableHttpClient.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (response!=null){
try {
response.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
@Test
public void test8() throws UnsupportedEncodingException {
//创建一个可关闭的httpclient客户端
CloseableHttpClient client = HttpClients.createDefault();
//URLEncoder给传送的字段转utf-8
String pwd1="asd123";
pwd1= URLEncoder.encode(pwd1,"UTF-8");
//创建一个url
String url2="https://mail.163.com/contacts/call.do?uid=xxxxxxxx&sid=xxxxxxxx&" +
"from=webmail&cmd=newapi.getContacts&vcardver=3.0&ctype=all&attachinfos=yellowpage,frequentContacts&freContLim=20";
//创建new 一个 httpGet(url)请求
HttpGet httpGet = new HttpGet(url2);
//添加一个httpclient.addheader的useragent防认为不是人为
httpGet.addHeader("user-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36");
//添加一个防盗链
httpGet.addHeader("referer","https://mail.163.com/js6/main.jsp?sid=xxxxxxxxr");
//创建一个空的 closeablehttpresponse
CloseableHttpResponse response=null;
//抛出一个异常
try {
//异常中使用可关闭的客户端.execute(httpget);返回一个可关闭的httpresponse
response= client.execute(httpGet);
HttpEntity entity = response.getEntity();
//获取response的对象,将其转化为String
String s1 = EntityUtils.toString(entity);
//输出
System.out.println(s1);
//释放被持有的所有资源,释放连接管理器,以便它可以处理下一个要求
EntityUtils.consume(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭可关闭的客户端和返会的response
if (client != null){
try {
client.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (response != null){
try {
response.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
@Test(description = "获取响应头以及响应的content-type")
public void test9() throws UnsupportedEncodingException {
//创建一个可关闭的httpclent可关闭的客户端
CloseableHttpClient bDefault = HttpClients.createDefault();
//urlEncoder将传输的密码转成utf-8
String pwd2="123456asd";
pwd2 = URLEncoder.encode(pwd2, "UTF-8");
//创建一个url路径
String url3="https://mail.163.com/contacts/call.do?uid=xxxxxxxx&sid=xxxxxxxx&" +
"from=webmail&cmd=newapi.getContacts&vcardver=3.0&ctype=all&attachinfos=yellowpage,frequentContacts&freContLim=20";
//添加一个httpclient的get请求:content-type,user-Agent,referer
HttpGet httpGet = new HttpGet(url3);
//添加一个httpcget.addheader的useragent防止机器认为不是人为操作
httpGet.addHeader("user-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/94.0.4606.81 Safari/537.36");
//添加一个防盗链referer
httpGet.addHeader("referer","https://mail.163.com/js6/main.jsp?sid=xxxxxxxx");
//创建一个可关闭的closeablihttpresponse
CloseableHttpResponse response=null;
//抛出一个异常
try {
//异常中使用可关闭的我客户端hhtpclient,返回一个httpreposne
response= bDefault.execute(httpGet);
/*
* 新知识:获取response.getStatusLine()进行判断
* 代表本次请求成功或者失败的状态
* */
StatusLine statusLine = response.getStatusLine();
//response.getAllHeaders();
//判断是否成功
if (HttpStatus.SC_OK==statusLine.getStatusCode()){
System.out.println("响应成功");
//获取response对象,转化成String
/*httpEntity不仅可以作为结果也可以作为请求结果参数实体,有很多的实现*/
HttpEntity entity3 = response.getEntity();
/*
获取contenttype
*/
Header contentType = entity3.getContentType();
System.out.println("contenttype结果是:"+contentType);
String s3 = EntityUtils.toString(entity3);
System.out.println(s3);
//确保流关闭
EntityUtils.consume(entity3);
}else {
System.out.println("相应失败,状态码为"+ statusLine.getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭可关闭的客户端
if (bDefault !=null){
try {
bDefault.close();
}catch (IOException e){
e.printStackTrace();
}
}
//关闭返回的response
if (response !=null){
try {
response.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
@Test(description = "获取网络上的图片保存到本地")
public void test10(){
//创建一个可关闭的客户端
CloseableHttpClient cclient=HttpClients.createDefault();
//船舰一个url路径
String uurl="";
//创建new一个httpclient的get请求
HttpGet httpGet = new HttpGet(uurl);
//添加一个httpget.addheader的useragent,防止机器认为不是认为操作
httpGet.addHeader("user-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36");
//添加一个防盗链referer
httpGet.addHeader("referer","https://mail.163.com/js6/main.jsp?sid=xxxxxxxxr");
//船舰一个可关闭的closeablehttpresponse
CloseableHttpResponse response4=null;
/*
抛出的异常中获取图片进行添加
*/
try {
CloseableHttpResponse execute = cclient.execute(httpGet);
HttpEntity entity4 = execute.getEntity();
String contentType = entity4.getContentType().getValue();
//image/jpg image/jpeg image/png image/图片后缀
String suffix=".jpg";
if (contentType.contains("jpg")||contentType.contains("kpeg")){
suffix=".jpg";
}else if (contentType.contains("bmp")||contentType.contains("bitmap")){
suffix=".bmp";
}else if (contentType.contains("png")){
suffix=".png";
}
//获取字节流
byte[] bytes = EntityUtils.toByteArray(entity4);
//放到绝对地址
String localAbspath="E:\\abc"+suffix;
FileOutputStream fos = new FileOutputStream(localAbspath);
//写入该字节
fos.write(bytes);
//关闭流
fos.close();
//关闭EntityUtils对象的entity4
EntityUtils.consume(entity4);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (cclient!=null){
try {
cclient.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (response4!=null){
try {
response4.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
@Test(description = "设置访问代理")
public void test11(){
CloseableHttpClient dDefault = HttpClients.createDefault();
String url5="https://www.baidu.com";
HttpGet httpGet = new HttpGet(url5);
/*
此处设置访问代理
可以找一些免费的网址进行使用
http://www.66ip.cn/
*/
String ip="202.201.13.182";
int port=80;
HttpHost httpHost = new HttpHost(ip,port);
//对每一个请求进行设置,会覆盖全局的默认请求配置
RequestConfig build = RequestConfig.custom()
.setProxy(httpHost)
.build();
httpGet.setConfig(build);
CloseableHttpResponse response5=null;
try {
CloseableHttpResponse execute = dDefault.execute(httpGet);
HttpEntity entity = execute.getEntity();
String s5 = EntityUtils.toString(entity);
System.out.println(s5);
EntityUtils.consume(entity);
}catch (Exception e){
e.printStackTrace();
}finally {
if (dDefault!=null){
try {
dDefault.close();
}catch (Exception e){
e.printStackTrace();
}
}
if (response5!=null){
try {
response5.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test(description = "连接超时和读取超时设置")
public void test12(){
//创建对象(输出的名字写上类,不然找不到)
Logger log = Logger.getLogger("TemplateExtendIntentMatcher:testTest");
// 输出信息
log.info("开始执行:1.创建一个可关闭的httpClient客户端");
//1.创建一个可关闭的httpClient客户端
CloseableHttpClient eclient = HttpClients.createDefault();
log.info("开始休息6s");
/* try {
Thread.sleep(6000);
}catch (InterruptedException e){
e.printStackTrace();
}*/
log.info("休息6s结束,执行httpget");
//2.new url()路径
String url6="http://www.testingedu.com.cn:8000/index.php/home/User/login.html";
//3.创建一个httpget请求
HttpGet httpGet = new HttpGet(url6);
log.info("httpget执行结束,对每一个请求设置,会对全局进行设置");
/* //=========设置访问代理,
String ip="202.201.13.182";
int Port=8080;
HttpHost httpHost = new HttpHost(ip, Port);*/
/*
* 连接超时和读取超时设置
* */ // 对每一个请求设置,会对全局进行设置
RequestConfig build=RequestConfig.custom()
//设置代理ip
//.setProxy(httpHost)
//设置连接超时,ms,完成tcp握手三次上限
.setConnectTimeout(1)
//读取超时,ms,表示从请求网址处获得响应数据的响应时间间隔
.setSocketTimeout(1)
//指从连接池获取connection超时时间
.setConnectionRequestTimeout(5000)
//构建
.build();
//4.添加addheader的user_agent的请求头,防止不是人为
httpGet.addHeader("user_agent","");
//5.添加addheader的referer的防盗链
httpGet.addHeader("referer","");
//6.创建一个可关闭空的closeablehttpresponse,
CloseableHttpResponse response6=null;
//抛出异常
try {
//7.异常中使用可关闭的客户端.execut(httpget);返回一个可关闭的httpresponse
response6 = eclient.execute(httpGet);
//8.使用返回的httprespponse对象,获取.getEntity();
HttpEntity entity = response6.getEntity();
//9.将获取的httpEntiy的response对象转换成String
String s6 = EntityUtils.toString(entity,StandardCharsets.UTF_8);
//10.输出或者断言
System.out.println(s6);
}catch (ClassCastException e){
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭可关闭的客户端eclient
if (eclient != null){
try {
eclient.close();
}catch (Exception e){
e.printStackTrace();
}
}
log.info("关闭可关闭的客户端response"+response6);
//关闭可关闭的客户端response
if (response6 != null){
try {
response6.close();
}catch (Exception e){
e.printStackTrace();
}
}
log.info("程序关闭完成且结束");
}
}
@Test(description = "发送application/x-www-form-urlencoded类型的post请求")
public void test13(){
Logger log=Logger.getLogger("tester");
log.info("创建一个可关闭的httpclient客户端");
CloseableHttpClient fclient = HttpClients.createDefault();
log.info("可以设置jenkins的网址");
String url="http://www.testingedu.com.cn:8000/index.php/home/User/login.html";
//创建一个httppost对象
HttpPost httpPost = new HttpPost(url);
//==========设置请求头,也可以不设置默认的===新加设置========
httpPost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
//设置post对象设置参数
/*
NameValuePair:相当于把<input id="user-name-label" type="text" name="username">
input标签中的属性name(username)输入的值构成了一个namevalurpail对象
*/
ArrayList<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("username","13800006"));
list.add(new BasicNameValuePair("password","123456"));
list.add(new BasicNameValuePair("verify_code","1111"));
//把参数集中设置到urlEncodedformEntity中
UrlEncodedFormEntity formentity = new UrlEncodedFormEntity(list,Consts.UTF_8);
//把formEntiy值设置到httppost对象中
httpPost.setEntity(formentity);
CloseableHttpResponse response=null;
try {
//获取客户端的.execut(httppost),返回一个response
response= fclient.execute(httpPost);
//获取response的getEntity类
HttpEntity entity = response.getEntity();
//使用Entityuntil的工具类转换成toString设置编码
String s7 = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println("s7:=============="+s7);
//这个啥意思
EntityUtils.consume(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭可关闭的fclient
if (fclient !=null){
try {
fclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭可关闭的response
if (response !=null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test(description = "发送application/json类型的post请求")
public void test14(){
Logger log=Logger.getLogger("tester");
log.info("创建一个可关闭的httpclient客户端");
CloseableHttpClient fclient = HttpClients.createDefault();
log.info("可以设置jenkins的网址");
//因为是页面网址不是接口所以登录不进去
String url="http://www.testingedu.com.cn:8000/index.php/home/User/login.html";
//===============================新内容===============================
//创建一个httppost对象
HttpPost httpPost = new HttpPost(url);
//给下面的StringEntity中的key值设置josnobject
JSONObject object = new JSONObject();
object.put("username","13800006");
object.put("password","123456");
object.put("verify_code","1111");
//new StringEntitity(null,consts.utf-8);String是一个接送字符串。jsonObject要转化成toString
StringEntity jsonEntity = new StringEntity(object.toString(), Consts.UTF_8);
//==========设置请求头,也可以不设置默认的===新加设置====给Entity设置一个内容类型====
//两种方法
// jsonEntity.setContentType("application/json; charset=utf-8");
jsonEntity.setContentType(new BasicHeader("Content-Type","application/json; charset=utf-8"));
//设置Entity编码
jsonEntity.setContentType(Consts.UTF_8.name());
//把formEntiy值设置到httppost对象中
httpPost.setEntity(jsonEntity);
//==============================================================
CloseableHttpResponse response=null;
try {
//获取客户端的.execut(httppost),返回一个response
response= fclient.execute(httpPost);
//获取response的getEntity类
HttpEntity entity = response.getEntity();
//使用Entityuntil的工具类转换成toString设置编码
String s7 = EntityUtils.toString(entity, StandardCharsets.UTF_8);
// System.out.println("s7:=============="+s7);
System.out.println("response.getAllHeaders();:=============="+response.getStatusLine().getStatusCode());
//获取登录状态
int statusCode = response.getStatusLine().getStatusCode();
//断言
Assert.assertEquals(200,statusCode);
//释放资源
EntityUtils.consume(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭可关闭的fclient
if (fclient !=null){
try {
fclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭可关闭的response
if (response !=null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test(description = "发送multipart/form-data类型上传文件的post请求,文件上传+普通表单参数的传递")
public void test15(){
//创建一个可关闭的httpclient对象
CloseableHttpClient gclient = HttpClients.createDefault();
//post请求url
String url="";
HttpPost httpPost = new HttpPost(url);
//=============================不同处===============================
//设置构造一个contentbody实现类对象
FileBody fileBody = new FileBody(new File("C:\\Users\\Admin\\Pictures\\1.jpg"));
//设置构造一个上传文件的entity
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Consts.UTF_8);//设置编码
//设置上传的ContentType,有中文的话会变乱码,所以第一个不用,用第二个
//builder.setContentType(ContentType.MULTIPART_FORM_DATA);
builder.setContentType(ContentType.create("MULTIPART_FORM_DATA",Consts.UTF_8));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器模式
/*
对于普通的表单字段如含有中文的话会乱码,下面不能使用addTextBody,换成addPart;先转换成Stringbody
text:值得是输入的username中文值
*/
StringBody usernamestringBody = new StringBody("小明中文字段",ContentType.create("text/plain",Consts.UTF_8));
//给MultipartEntityBuilder的entity设置HttpEntity上传参数
HttpEntity httpEntity = builder.addPart("filename", fileBody)
.addBinaryBody("filename",new File("C:\\Users\\Admin\\Pictures\\1.jpg"))
//.addTextBody("username","中文字段")//有中文不用addTextBody
.addPart("username",usernamestringBody)
.addTextBody("password","123456")
.build();
//给httppost.setEntity值
httpPost.setEntity(httpEntity);
//============================================================
//设置一个可关闭的CloseableHttpResponse
CloseableHttpResponse response=null;
//抛异常
try {
//获取客户端的.execut(httpPost); 返回一个response
response=gclient.execute(httpPost);
//获取response的.getEntity()应该是实体类,
HttpEntity entity = response.getEntity();
//转化成toString
String s9 = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println("s9"+s9);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭可关闭的gclient
if (gclient !=null){
try {
gclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭可关闭的response
if (response !=null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test(description = "如何绕过https的安全验证")
public void test16() throws Exception {
Logger log=Logger.getLogger("tester");
log.info("创建一个可关闭的httpclient客户端");
//===================================================================================
//构建一个信任的对象
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("htpps", trusHttpCertificates())
.build();
//2.创建一个PoolingHttpClientConnectionManager
PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager(registry);
//1.定制CloseableHttpClient;
//完成之后转成对象,将下面的HttpClients.createDefault()替换成httpClientBuilder.build()
HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(pool);
/*这里后面需要替换,配置好httpclient之后,通过build方法来获得httpclient对象*/
//使用HttpClients.createDefault()在不安全的连接上是报错的
//CloseableHttpClient fclient = HttpClients.createDefault();
CloseableHttpClient fclient = httpClientBuilder.build();
//========================================================================================
log.info("可以设置jenkins的网址");
//因为是页面网址不是接口所以登录不进去
String url="http://www.testingedu.com.cn:8000/index.php/home/User/login.html";
//===============================新内容===============================
//创建一个httppost对象
HttpPost httpPost = new HttpPost(url);
//给下面的StringEntity中的key值设置josnobject
JSONObject object = new JSONObject();
object.put("username","13800006");
object.put("password","123456");
object.put("verify_code","1111");
//new StringEntitity(null,consts.utf-8);String是一个接送字符串。jsonObject要转化成toString
StringEntity jsonEntity = new StringEntity(object.toString(), Consts.UTF_8);
//==========设置请求头,也可以不设置默认的===新加设置====给Entity设置一个内容类型====
//两种方法
// jsonEntity.setContentType("application/json; charset=utf-8");
jsonEntity.setContentType(new BasicHeader("Content-Type","application/json; charset=utf-8"));
//设置Entity编码
jsonEntity.setContentType(Consts.UTF_8.name());
//把formEntiy值设置到httppost对象中
httpPost.setEntity(jsonEntity);
//==============================================================
CloseableHttpResponse response=null;
try {
//获取客户端的.execut(httppost),返回一个response
response= fclient.execute(httpPost);
//获取response的getEntity类
HttpEntity entity = response.getEntity();
//使用Entityuntil的工具类转换成toString设置编码
String s7 = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println("s7:=============="+s7);
//这个啥意思
EntityUtils.consume(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭可关闭的fclient
if (fclient !=null){
try {
fclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭可关闭的response
if (response !=null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
*构建支持安全协议的连接工厂
*/
private ConnectionSocketFactory trusHttpCertificates() throws Exception {
//2.sslContext爆红,需要构键SSLContextBuilder 的sslContextBuilder.build()
SSLContextBuilder sslContextBuilder= new SSLContextBuilder();
//4.构建之前需要sslContextBuilder.loadTrustMaterial加载信任所有的url
sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
//isTrusted判断是否信任url,直接返回true就可以了
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
});
//3.有异常要抛出
SSLContext sslContext = sslContextBuilder.build();
//1.创建连接工厂new SSLConnectionSocketFactory对象进行设置
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext,
//可以通过的协议
new String[]{"SSLV2Hello","SSLv3","TLSv1","TLSv1.1","TLSv1.2"}
,null, NoopHostnameVerifier.INSTANCE);
//最后返回sslConnectionSocketFactory
return sslConnectionSocketFactory;
}
}
httpclient接口自动化全部代码【搬代码】
于 2022-07-22 21:15:58 首次发布