已知两种方法。一种是通过httpclient实现(貌似很简单,以后看一下),一种是以下方法:

Client实现:

package common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map; /**
* Created by zipon on 2018/8/27.
*/
public class HttpClientUtil {
Logger log = new LogUtil("http_log").logger;
/**
* Post方式 得到JSONObject
*
* @param params post参数
* @param url
* @encoding 编码格式,这里直接写死为utf-8
* @return
*/
public JSONObject doPost(JSONObject params, String url) throws IOException {
//创建httpClient连接
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null; JSONObject resultJsonObject = new JSONObject();
try {
StringEntity entity = new StringEntity(params.toString(),"utf-8");
HttpPost httpPost = new HttpPost(url);
//httpPost.addHeader("Content-Type","application/json");
// 为HttpPost设置实体数据
httpPost.setEntity(entity);
log.info("******************请求开始********************");
log.info(String.format("请求url信息:%s",httpPost.getRequestLine()));
log.info("请求headers信息:");
String headerList ="";
for (Header header :httpPost.getAllHeaders()){
headerList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info(headerList);
log.info("请求body:");
log.info(httpEntityToJSONObject(httpPost.getEntity()));
// HttpClient 发送Post请求
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// CloseableHttpResponse
HttpEntity httpEntity = httpResponse.getEntity();
resultJsonObject = httpEntityToJSONObject(httpEntity);
}else{
resultJsonObject.put("errorMessage",httpResponse);
}
log.info("返回headers信息:");
log.info(httpResponse.getAllHeaders());
log.info("返回body:");
log.info(httpResponse.getEntity());
log.info("******************请求结束********************");
} catch (Exception e) {
e.printStackTrace();
}finally {
httpResponse.close();
httpClient.close();
}
return resultJsonObject;
} /**
* 没有headers 没有cookie插入的快速post
* @param params
* @param url
* @return
* @throws IOException
*/
// public BaseResponse doPost(JSONObject params, String url) throws IOException {
// //创建httpClient连接
// CloseableHttpClient httpClient = HttpClients.createDefault();
// CloseableHttpResponse httpResponse = null;
//
// BaseResponse baseResponse = new BaseResponse();
// try {
// StringEntity entity = new StringEntity(params.toString(),"utf-8");
// HttpPost httpPost = new HttpPost(url);
// // 为HttpPost设置实体数据
// httpPost.setEntity(entity);
//// 默认Content-Type
// httpPost.addHeader("Content-Type","application/json");
// System.out.println(httpEntityToJSONObject(httpPost.getEntity()));
// // HttpClient 发送Post请求
// httpResponse = httpClient.execute(httpPost);
// baseResponse = httpResponseToBaseResponse(httpResponse);
//
// } catch (Exception e) {
// e.printStackTrace();
// }finally {
// httpResponse.close();
// httpClient.close();
// }
// return baseResponse;
// } /**
* 主用这个
* @param params
* @param url
* @param headers
* @param cookie
* @return
* @throws IOException
*/
public BaseResponse doPost(JSONObject params, String url ,JSONObject headers ,String cookie) throws IOException {
//创建httpClient连接
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null; BaseResponse baseResponse = new BaseResponse();
try {
HttpPost httpPost = new HttpPost(url);
StringEntity entity;
if (headers.get("Content-Type")=="application/x-www-form-urlencoded") {
List<NameValuePair> pairs = new ArrayList<>(32);
for (String key : params.keySet()) {
pairs.add(new BasicNameValuePair(key,params.get(key).toString()));
}
log.info(pairs);
entity = new UrlEncodedFormEntity(pairs,"utf-8");
}
else {
entity = new StringEntity(params.toString(), "utf-8");
}
addHeaders(httpPost,headers);
addCookies(httpPost,cookie);
log.info("******************请求开始********************");
log.info(String.format("请求url信息:%s",httpPost.getRequestLine()));
String headerList ="";
for (Header header :httpPost.getAllHeaders()){
headerList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info("请求headers信息:\r\n"+headerList.substring(0,headerList.length()-2));
// httpPost.addHeader("Content-Type","application/json");
// 为HttpPost设置实体数据
httpPost.setEntity(entity);
log.info("请求body:\n"+httpEntityToJSONObject(httpPost.getEntity()));
// log.info(httpEntityToJSONObject(httpPost.getEntity()));
// HttpClient 发送Post请求
httpResponse = httpClient.execute(httpPost);
baseResponse = httpResponseToBaseResponse(httpResponse);
String repheaderList ="";
for (Header header :httpResponse.getAllHeaders()){
repheaderList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info("返回headers信息: \r\n"+repheaderList.substring(0,repheaderList.length()-2));
log.info("返回body:\n"+baseResponse.getResponseBody());
// log.info(baseResponse.getResponseBody());
log.info("******************请求结束********************"); } catch (Exception e) {
e.printStackTrace();
}finally {
httpResponse.close();
httpClient.close();
}
return baseResponse;
} //
// public JSONObject getJSONObjectByGet(String url) throws IOException {
// JSONObject resultJsonObject=null;
//
// //创建httpClient连接
// CloseableHttpClient httpClient = HttpClients.createDefault();
// // HttpClient 发送Post请求
// CloseableHttpResponse httpResponse = null;
// try{
// StringBuilder urlStringBuilder=new StringBuilder(url);
// //利用URL生成一个HttpGet请求
// HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
//// httpGet.setHeader("Content-Type","text/123");
// System.out.println(httpGet.getMethod());
// for (Header header :httpGet.getAllHeaders()){
// String key = header.getName();
// String value = header.getValue();
// System.out.println(String.format("%s:%s",key,value));
// }
// System.out.println(httpGet.getProtocolVersion());
// System.out.println(httpGet.getRequestLine());
//
// httpResponse=httpClient.execute(httpGet);
// } catch (Exception e) {
// e.printStackTrace();
// }finally{
// httpResponse.close();
// httpClient.close();
// }
// //得到httpResponse的状态响应码
// if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK) {
// //得到httpResponse的实体数据
// HttpEntity httpEntity=httpResponse.getEntity();
// resultJsonObject = httpEntityToJSONObject(httpEntity);
// }
// return resultJsonObject;
// } /**
* 不带headers、cookies参数的get请求
* @param url
* @return
* @throws IOException
*/
public BaseResponse doGet(String url) throws IOException {
//创建httpClient连接
CloseableHttpClient httpClient = HttpClients.createDefault();
// HttpClient 发送get请求
CloseableHttpResponse httpResponse = null;
BaseResponse baseResponse = new BaseResponse();
try{
StringBuilder urlStringBuilder=new StringBuilder(url);
//利用URL生成一个HttpGet请求
HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
log.info("******************请求开始********************");
log.info(String.format("请求url信息:%s",httpGet.getRequestLine()));
String headerList ="";
for (Header header :httpGet.getAllHeaders()){
headerList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info("请求headers信息:\r\n"+headerList.substring(0,headerList.length()-2));
httpResponse=httpClient.execute(httpGet);
baseResponse = httpResponseToBaseResponse(httpResponse);
String repheaderList ="";
for (Header header :httpResponse.getAllHeaders()){
repheaderList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info("返回headers信息: \r\n"+repheaderList.substring(0,repheaderList.length()-2));
log.info("返回body:");
log.info(baseResponse.getResponseBody());
log.info("******************请求结束********************");
} catch (Exception e) {
e.printStackTrace();
}finally{
httpResponse.close();
httpClient.close();
}
return baseResponse;
} public BaseResponse doGet(String url,JSONObject headers,String cookies) throws IOException {
//创建httpClient连接
CloseableHttpClient httpClient = HttpClients.createDefault();
// HttpClient 发送get请求
CloseableHttpResponse httpResponse = null;
BaseResponse baseResponse = new BaseResponse();
try{
StringBuilder urlStringBuilder=new StringBuilder(url);
//利用URL生成一个HttpGet请求
HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
addHeaders(httpGet,headers);
addCookies(httpGet,cookies);
log.info("******************请求开始********************");
log.info(String.format("请求url信息:%s",httpGet.getRequestLine()));
String headerList ="";
for (Header header :httpGet.getAllHeaders()){
headerList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info("请求headers信息:\r\n"+headerList.substring(0,headerList.length()-2));
httpResponse=httpClient.execute(httpGet);
baseResponse = httpResponseToBaseResponse(httpResponse);
String repheaderList ="";
for (Header header :httpResponse.getAllHeaders()){
repheaderList += header.getName()+":"+header.getValue()+"\r\n";
}
log.info("返回headers信息: \r\n"+repheaderList.substring(0,repheaderList.length()-2));
log.info("返回body:");
log.info(baseResponse.getResponseBody());
log.info("******************请求结束********************");
} catch (Exception e) {
e.printStackTrace();
}finally{
httpResponse.close();
httpClient.close();
}
return baseResponse;
} /**
* 将HttpEntity类转换为JSONObject封装方法,表单键值对格式直接put到formData里去
* @param httpEntity
* @return
*/
public JSONObject httpEntityToJSONObject(HttpEntity httpEntity){
StringBuilder entityStringBuilder=new StringBuilder();
JSONObject resultJsonObject=new JSONObject();
String jsonStr=null;
if (httpEntity!=null) {
BufferedReader reader=null;
try {
reader=new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024);
String line=null;
while ((line=reader.readLine())!=null) {
entityStringBuilder.append(line);
}
// 从HttpEntity中得到的json String数据转为json
jsonStr=entityStringBuilder.toString();
resultJsonObject=JSON.parseObject(jsonStr);
} catch (JSONException e) {
//如果不是json格式的,应该是表单键值对格式,直接put到formData
resultJsonObject.put("formData",jsonStr);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
//关闭流
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return resultJsonObject;
} /**
* 将httpResponse对象转换为自定义的BaseResponse对象
* @param httpResponse
* @return
*/
public BaseResponse httpResponseToBaseResponse(CloseableHttpResponse httpResponse){
// 遍历取出headers
JSONArray headList = new JSONArray();
for (Header header :httpResponse.getAllHeaders()){
String key = header.getName();
String value = header.getValue();
JSONObject tempJson = new JSONObject();
tempJson.put(key,value);
headList.add(tempJson);
}
BaseResponse baseResponse = new BaseResponse();
baseResponse.setHeaders(headList);
baseResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
baseResponse.setResponseBody(httpEntityToJSONObject(httpResponse.getEntity())); return baseResponse;
} /**
* 为httpGet和httpPost加headers
* @param httpEntityEnclosingRequestBase,HttpGet和HttpPost都是继承这个类
* @param headers
* @return
*/
public HttpEntityEnclosingRequestBase addHeaders(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase, JSONObject headers){
//循环加header
if(headers!=null) {
for (Map.Entry<String, Object> entry : headers.entrySet()) {
httpEntityEnclosingRequestBase.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
}
}
return httpEntityEnclosingRequestBase;
}
/**
* 为httpGet加headers
* @param httpRequestBase,HttpGet和HttpPost都是继承这个类
* @param headers
* @return
*/
public HttpRequestBase addHeaders(HttpRequestBase httpRequestBase, JSONObject headers){
//循环加header
if(headers!=null) {
for (Map.Entry<String, Object> entry : headers.entrySet()) {
httpRequestBase.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
}
}
return httpRequestBase;
} /**
* 为httpPost加cookies
* @param httpEntityEnclosingRequestBase,HttpPost是继承这个类
* @param cookies
* @return
*/
public HttpEntityEnclosingRequestBase addCookies(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase,String cookies){
//循环加cookies
if(cookies!=null) {
httpEntityEnclosingRequestBase.addHeader("Cookie", cookies);
}
return httpEntityEnclosingRequestBase;
}
/**
* 为httpPost加cookies
* @param httpRequestBase,HttpGet是继承这个类
* @param cookies
* @return
*/
public HttpRequestBase addCookies(HttpRequestBase httpRequestBase, String cookies){
//循环加cookies
if(cookies!=null) {
httpRequestBase.addHeader("Cookie", cookies);
}
return httpRequestBase;
} }
 import java.io.*;
import java.net.URL;
import java.net.URLConnection; /**
* @author kin
* @version $: v 0.1 2016/8/23 Exp $$
*/
public class httpTest { public static void sendGet() throws IOException { BufferedReader in1 = null;
// 1.创建URL类
URL urlString = new URL("https://www.baidu.com"); // 2.打开和URL之间的连接
URLConnection connection1 = urlString.openConnection(); // 3.设置通用的请求属性 connection1.setRequestProperty("accept", "*/*");
connection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8;");
connection1.setRequestProperty("connection", "Keep-Alive");
connection1.setRequestProperty("user-agent", "testDemo"); // 4.建立实际的连接
connection1.connect(); // 5.定义 BufferedReader输入流来读取URL的响应
in1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
String line = null;
while ((line = in1.readLine()) != null) {
System.out.println(line);
} // 6.使用finally块来关闭输入流
in1.close();
} public static void sendPost(String data) {
String charSet = "utf-8";
BufferedReader in1 = null;
PrintWriter out = null;
// 1.创建URL类
try {
URL urlPost = new URL("http://www.baidu.com"); // 2.打开和URL之间的连接 URLConnection connectionPost = urlPost.openConnection();
// 3.设置通用的请求属性
connectionPost.setConnectTimeout(30000);
connectionPost.setReadTimeout(30000);
connectionPost.setRequestProperty("accept", "*/*");
connectionPost.setRequestProperty("Content-Type", "application/json;charset=" + charSet);
connectionPost.setRequestProperty("connection", "Keep-Alive");
connectionPost.setRequestProperty("user-agent", "testDemoPost");
// 4.建立实际的连接
connectionPost.connect(); // 5.发送post请求必须设置如下两行,设置了这两行,就可以对URL连接进行输入/输出 connectionPost.setDoInput(true);
connectionPost.setDoOutput(true);
// 6.获取URLConnection对象对应的输出流 out = new PrintWriter(new OutputStreamWriter(connectionPost.getOutputStream(), charSet)); // 7.发送请求参数
out.print(data); // 8.清空缓存区的缓存
out.flush(); // 9.定义 BufferedReader输入流来读取URL的响应
in1 = new BufferedReader(new InputStreamReader(connectionPost.getInputStream(), charSet)); } catch (IOException e) {
e.printStackTrace();
}// 10.使用finally块来关闭输入流
finally {
try {
out.close();
in1.close();
}catch(Exception e){
e.printStackTrace();
} }
}
public static void main(String[] args) throws IOException {
httpTest.sendGet();
} }

接口自动化测试框架--http请求的get、post方法的实现的更多相关文章

  1. 接口自动化 [授客]基于python+Testlink+Jenkins实现的接口自动化测试框架V3.0

    基于python+Testlink+Jenkins实现的接口自动化测试框架V3.0   by:授客 QQ:1033553122     博客:http://blog.sina.com.cn/ishou ...

  2. 基于python+Testlink+Jenkins实现的接口自动化测试框架V3.0

    基于python+Testlink+Jenkins实现的接口自动化测试框架V3.0 目录 1. 开发环境2. 主要功能逻辑介绍3. 框架功能简介 4. 数据库的创建 5. 框架模块详细介绍6. Tes ...

  3. 【转】robot framework + python实现http接口自动化测试框架

    前言 下周即将展开一个http接口测试的需求,刚刚完成的java类接口测试工作中,由于之前犯懒,没有提前搭建好自动化回归测试框架,以至于后期rd每修改一个bug,经常导致之前没有问题的case又产生了 ...

  4. 【python3+request】python3+requests接口自动化测试框架实例详解教程

    转自:https://my.oschina.net/u/3041656/blog/820023 [python3+request]python3+requests接口自动化测试框架实例详解教程 前段时 ...

  5. 接口自动化 基于python实现的http+json协议接口自动化测试框架源码(实用改进版)

    基于python实现的http+json协议接口自动化测试框架(实用改进版)   by:授客 QQ:1033553122 欢迎加入软件性能测试交流QQ群:7156436     目录 1.      ...

  6. robot framework + python实现http接口自动化测试框架

    https://www.jianshu.com/p/6d1e8cb90e7d 前言 下周即将展开一个http接口测试的需求,刚刚完成的java类接口测试工作中,由于之前犯懒,没有提前搭建好自动化回归测 ...

  7. python+requests接口自动化测试框架实例详解

    python+requests接口自动化测试框架实例详解   转自https://my.oschina.net/u/3041656/blog/820023 摘要: python + requests实 ...

  8. Python接口自动化测试框架实战 从设计到开发

    第1章 课程介绍(不要错过)本章主要讲解课程的详细安排.课程学习要求.课程面向用户等,让大家很直观的对课程有整体认知! 第2章 接口测试工具Fiddler的运用本章重点讲解如何抓app\web的htt ...

  9. 接口自动化测试框架【windows版】:jmeter + ant + jenkins

    为了提高回归效率及保证版本质量,很多公司都在做自动化测试,特别是接口自动化.接口自动化测试框架很多,有写代码的,也有不写代码的,我觉得没有谁比谁好,谁比谁高级之说,只要适用就好. 今天给大家分享一个不 ...

随机推荐

  1. NBUT 1114 Alice's Puppets(排序统计,水)

    题意:给一棵人名树,按层输出,同层则按名字的字典序输出. 思路:首先对每个人名做索引,确定其在哪一层,按层装进一个set,再按层输出就自动排好序了. #include <bits/stdc++. ...

  2. lua_to_luac

    #!/bin/sh `rm -rf allLua.zip` `mkdir ./tempScripts` `mkdir ./tempScripts/scripts` `cp -a ./scripts/ ...

  3. OpenGL 渲染上下文-context

    context理解 OpenGL在渲染的时候需要一个Context,这个Context记录了OpenGL渲染需要的所有信息,可以把它理解成一个大的结构体,它里面记录了当前绘制使用的颜色.是否有光照计算 ...

  4. 自己太水了—HDOJ_2212

    Problem Description A DFS(digital factorial sum) number is found by summing the factorial of every d ...

  5. (四)VMware Harbor 配置文件

    VMware Harbor 配置文件 :harbor.yml # Configuration file of Harbor # The IP address or hostname to access ...

  6. java POI技术之导出数据优化(15万条数据1分多钟)

    专针对导出excel2007 ,用到poi3.9的jar package com.cares.ynt.util; import java.io.File; import java.io.FileOut ...

  7. HTML5触摸事件

    touchstart .touchmove .touchend 事件 touchstart事件:当手指触摸屏幕时触发,即使有一个手指放在屏幕上也会触发. touchmove事件:当手指在屏幕上滑动时触 ...

  8. docker系列之安装配置-2

    1.docker安装 1.CentOS Docker 安装 Docker支持以下的CentOS版本: CentOS 7 (64-bit) CentOS 6.5 (64-bit) 或更高的版本 目前,C ...

  9. CVS在update时状态status

    cvs update -Ad 时,terminal 会display如下: P xx.v P xx.c ? xx.v ? xx.c A xx.v M xx.v U xx.v C xx.v 第一个字母: ...

  10. python-leepcode-作用解析 - 5-27

    30 找不同 给定两个字符串 s 和 t,它们只包含小写字母. 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母. 请找出在 t 中被添加的字母. 示例: 输入: s = "a ...