自动化框架httpClient实例
package com.auto.test.util;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.execchain.RequestAbortedException;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*
* 2016年9月12日下午8:37:22
*/
public class HttpRequest {
private final static Logger logger=LoggerFactory.getLogger(HttpRequest.class);
private static final CloseableHttpClient httpClient;
static{
RequestConfig config=RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
httpClient=HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
public static final String CHARSET_utf="utf-8";
public static final String CHARSET_gbk = "GBK";
/**
* HTTP Post 获取内容
*
* @param url 请求的url地址 ?之前的地址
* @param params 表单参数
* @param heads 请求的头
* @param charset 编码格式
* @return 页面内容
*/
public static String doPostFormWithHeader(String url, Map<String, Object> params, Map<String, String> heads, String charset) {
if (StringUtils.isBlank(url)) {
return null;
}
System.out.println(url);
try {
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> pairs = null;
if (params != null && !params.isEmpty()) {
pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
String value = entry.getValue().toString();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
}
if (pairs != null && pairs.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET_utf));
}
if (heads != null) {
for (Entry<String, String> e : heads.entrySet()) {
httpPost.addHeader(e.getKey(), e.getValue());
}
}
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
if (e instanceof RequestAbortedException || e instanceof SocketTimeoutException || e instanceof SocketException) {
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return doPostFormWithHeader(url, params, heads, charset);
}
e.printStackTrace();
}
return null;
}
/**
* HTTP Post 获取内容
*
* @param params 请求的实体数据,非表单参数
* @param heads 请求的头
* @param charset 编码格式
* @return 页面内容
*/
public static String doPostBody(String urlInit, Map<String, Object> params, Map<String, String> heads, String charset) {
if (StringUtils.isBlank(urlInit)) {
return null;
}
// String url = urlInit + "?ticket=" + heads.get("ticket");
String url = urlInit;
try {
HttpPost httpPost = new HttpPost(url);
if (params != null && !params.isEmpty()) {
logger.info("[相关http参数]-"+JsonParse.map2Json(params));
StringEntity myEntity = new StringEntity(JsonParse.map2Json(params), charset);
httpPost.setEntity(myEntity);
}
if (heads != null) {
for (Entry<String, String> e : heads.entrySet()) {
httpPost.addHeader(e.getKey(), e.getValue());
}
}
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
logger.info("【URL】-" + url);
logger.info("[返回结果]-" + result);
httpPost.abort();
// throw new RuntimeException("HttpClient,error status code :" + statusCode);
logger.error("HttpClient,error status code :" + statusCode);
return result;
}
if (!JsonParse.getFromKey("ResultCode", result).equals("0")) {
logger.info("[返回结果]-" + result);
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
if (e instanceof RequestAbortedException || e instanceof SocketTimeoutException || e instanceof SocketException) {
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return doPostBody(url, params, heads, charset);
}
e.printStackTrace();
}
return null;
}
}
自动化框架httpClient实例的更多相关文章
- ASP.NET Core 6框架揭秘实例演示[17]:利用IHttpClientFactory工厂来创建HttpClient
在一个采用依赖注入框架的应用中,我们一般不太推荐利用手工创建的HttpClient对象来进行HTTP调用,使用的HttpClient对象最好利用注入的IHttpClientFactory工厂来创建.前 ...
- ASP.NET Core 6框架揭秘实例演示[18]:HttpClient处理管道
我们知道ASP.NET的核心就是由中间件组成的请求处理管道,HttpClient也采用了类似的设计.HttpClient管道由一组HttpMessageHandler对象构成,这些HttpMessag ...
- python+requests接口自动化框架
为什么要做接口自动化框架 1.业务与配置的分离 2.数据与程序的分离:数据的变更不影响程序 3.有日志功能,实现无人值守 4.自动发送测试报告 5.不懂编程的测试人员也可以进行测试 正常接口测试的流程 ...
- CYQ.Data 从入门到放弃ORM系列:开篇:自动化框架编程思维
前言: 随着CYQ.Data 开始回归免费使用之后,发现用户的情绪越来越激动,为了保持这持续的激动性,让我有了开源的念头. 同时,由于框架经过这5-6年来的不断演进,以前发的早期教程已经太落后了,包括 ...
- 接口自动化:HttpClient + TestNG + Java(二) - 第一个接口测试:get请求
在上一篇中,我们搭建好了HttpClient + TestNG + Java的自动化接口测试环境,这一篇我们就赶紧开始编写我们的第一个接口测试用例. 本篇会对问题解决的思路进行更详尽的阐述. 2.1 ...
- 接口自动化框架(Pytest+request+Allure)
前言: 接口自动化是指模拟程序接口层面的自动化,由于接口不易变更,维护成本更小,所以深受各大公司的喜爱. 接口自动化包含2个部分,功能性的接口自动化测试和并发接口自动化测试. 本次文章着重介绍第一种, ...
- ShutIt:一个基于 Python 的 shell 自动化框架
ShutIt是一个易于使用的基于shell的自动化框架.它对基于python的expect库(pexpect)进行了包装.你可以把它看作是“没有痛点的expect”.它可以通过pip进行安装. Hel ...
- ui自动化笔记 selenium_webdriver,ui自动化框架(web)
Selenium学习笔记 selenium webdriver是业界公认ui自动化测试的标准,其封装的api可以对浏览器的任何地方进行操作 selenium2.0和selenium3.0的区别? 3. ...
- Jmeter+ant+Jenkins接口自动化框架搭建
摘自:https://testerhome.com/topics/13389 一.背景 上一篇讲了Jmeter 接口自动化-脚本数据分离实例,我们知道怎么利用Jmeter去编写接口自动化脚本,但是接 ...
随机推荐
- hostname -f 失败解决办法
$ hostname fzk $ uname -n fzk 当 hostname -f 时报错:未搜索到主机名 产生这个原因时因为 /etc/hosts和/etc/sysconfig/network ...
- hadoop02---高可用网站架构
tomcat每个请求都会占用内存cpu,tomcat没有代理功能.nginx是俄国人写的,nginx是静态资源服务器,既可以自己返回请求,也可以做代理进行转发,和负载均衡.Tomcat是动态资源jav ...
- java利用反射将pojo转为json对象
最近做以太坊钱包项目需要与前台进行json交互,写一个工具类,经普通javaBean转为json对象 package util; import java.lang.reflect.Field; imp ...
- 常用display属性
table 1. 宽高由内容撑开 2.独占一行 3.可设置宽高 4.可设置margin.padding inline-table 与display: table大体一致,区别在于不独占一行,为行内元素 ...
- 用nodejs实现读取文件操作
//如果不是全局就得引入fs成员 const fs = require("fs"); //fs 核心模块中提供了一个 fs.readFile方法,来读取指定目录下的文件 //fs. ...
- mongodb 的安装(Centor OS )
1.下载地址 wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.4.2.tgz 2.解压.配置 tar zxvf mongodb ...
- java基础(5)-集合类1
集合的由来 数组是很常用的一种数据结构,但假如我们遇到以下这样的的问题: 容器长度不确定 能自动排序 存储以键值对方式的数据 如果遇到这样的情况,数组就比较难满足了,所以也就有了一种与数组类似的数据结 ...
- QT 实现按住鼠标左键点击对话框空白处,拖动对话框
定义头文件 QPoint move_point; //移动的距离 bool mouse_press; //按下鼠标左键 protected: void mousePressEvent( ...
- dataframe按值(非索引)查找多行
很多情况下,我们会根据一个dataframe里面的值来查找而不是根据索引来查找. 首先我们创建一个dataframe: >>> col = ["id"," ...
- pandas read_sql与read_sql_table、read_sql_query 的区别
一:创建链接数据库引擎 from sqlalchemy import create_engine db_info = {'user':'user', 'password':'pwd', 'host': ...