接口测试 接口封装,支持大多数协议

BlackSword for BlackTest · 2018年11月22日 · 最后由 冷月醉夕阳 回复于 2018年12月12日 · 3719 次阅读

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import jodd.util.StringUtil;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.entity.ContentType;
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.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpUtils_Basics {

private final static Logger logger = LoggerFactory.getLogger(HttpUtils_Basics.class);

public static String doPostJson(String url, Object object, Map headers) {
// 创建 Httpclient 对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";

String requestData;
if (object instanceof String) {
requestData = (String) object;
} else {
requestData = JSONObject.toJSONString(object);
}

try {
// 创建 Http Post 请求
HttpPost httpPost = new HttpPost(url);
// 添加 http headers
if (headers != null && headers.size() > 0) {
for (String key : headers.keySet()) {
httpPost.addHeader(key, headers.get(key));
}
}
// 创建请求内容
StringEntity entity = new StringEntity(requestData, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行 http 请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return resultString;
}

public static String post(String url, Object object) throws Exception {
return post(url, object, null);
}

public static String post(String url, Object object, Map headers) throws Exception {
String responseMessage;
try {
HttpClient httpClient = HttpClients.createDefault();
HttpPost method = new HttpPost(url);
String requestData;
if (object instanceof String) {
requestData = (String) object;
} else {
requestData = JSONObject.toJSONString(object);
}
StringEntity entity = new StringEntity(requestData, "utf-8");
entity.setContentEncoding("utf-8");
entity.setContentType("application/json");
method.setEntity(entity);

if (headers != null) {
for (Map.Entry entry : headers.entrySet()) {
method.setHeader(entry.getKey(), entry.getValue());
}
}

HttpResponse result = httpClient.execute(method);

responseMessage = EntityUtils.toString(result.getEntity()); //响应内容

if (result.getStatusLine().getStatusCode() != 200) {
throw new Exception();
}
} catch (Exception e) {
logger.info("请求失败:" + e.getMessage());
throw new Exception();
}
return responseMessage;
}

/**
* get 请求
*
* @param url
* @param params
* @return
* @throws Exception
*/
public static String get(String url, Map params) throws Exception {
try {
if (StringUtil.isBlank(url)) return "";
String parStr = getUrlStrParams(params);
if (StringUtil.isNotBlank(parStr)) url += "?" + parStr;
HttpClient httpClient = HttpClients.createDefault();
HttpGet method = new HttpGet(url);

HttpResponse result = httpClient.execute(method);
String responseMessage = EntityUtils.toString(result.getEntity()); //响应内容
if (result.getStatusLine().getStatusCode() != 200) {
throw new Exception();
}
return responseMessage;
} catch (Exception e) {
logger.info("请求失败:" + e.getMessage());
throw new Exception();
}
}

/**
* 使用 HttpURLConnection 发送 Post 请求
*
* @param urlParam
* @param params
* @return
*/
public static String sendPost(String urlParam, Map params) {
StringBuffer resultBuffer = null;
String charset = "utf-8";
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Map.Entry e : params.entrySet()) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
}
HttpURLConnection con = null;
OutputStreamWriter osw = null;
BufferedReader br = null;
// 发送请求
try {
URL url = new URL(urlParam);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (sbParams != null && sbParams.length() > 0) {
osw = new OutputStreamWriter(con.getOutputStream(), charset);
osw.write(sbParams.substring(0, sbParams.length() - 1));
osw.flush();
}
// 读取返回内容
resultBuffer = new StringBuffer();
int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
if (contentLength > 0) {
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
}

return resultBuffer.toString();
}

/**
* 解析数据为 url 格式
*
* @param params
* @return
*/
public static String getUrlStrParams(Map params) {
if (params == null) return "";
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Map.Entry e : params.entrySet()) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
}
if (sbParams != null && sbParams.length() > 0) return sbParams.substring(0, sbParams.length() - 1);
return "";
}

public static String doPost(String url, Map param) {
// 创建 Httpclient 对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建 Http Post 请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List paramList = new ArrayList();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行 http 请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return resultString;
}

public static String doGet(String url, String param, Map headers, int timeout) {
String result = "";
BufferedReader in = null;
String reqUrl = url + "?" + param;
try {
// 构造 httprequest 设置
RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout).build();
HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
HttpGet htGet = new HttpGet(reqUrl);
// 添加 http headers
if (headers != null && headers.size() > 0) {
for (String key : headers.keySet()) {
htGet.addHeader(key, headers.get(key));
}
}
// 读取数据
HttpResponse r = client.execute(htGet);
in = new BufferedReader(new InputStreamReader(r.getEntity().getContent(), Charsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 GET 请求出现异常!" + e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in = null;
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
}

附带上部分 maven


org.jodd
jodd-http
5.0.6


com.alibaba
fastjson
1.2.51

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->

com.google.guava
guava
27.0-jre


org.slf4j
slf4j-nop
1.7.2

共收到 1 条回复 时间 点赞

接口是应用层,跟协议有什么关系

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册