Java后台模拟发送http的get和post请求,并测试

时间:2022-07-22 08:49:48

个人学习使用:谨慎参考

1 Client类

import com.thoughtworks.gauge.Step;
import com.thoughtworks.gauge.Table;
import com.thoughtworks.gauge.TableRow; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /**
* Created by KSC on 2/7/2017.
*/
public class testClient { //send get request /**
*
* @param url destination address
* @param parametersTable request parameters
* @return remote response result
*/
@Step("the get method url is <url> and parameters are <parametersTable>")
public static String sendGet(String url,Table parametersTable){
Map<String,String> parameters = new HashMap<>(); for(TableRow row : parametersTable.getTableRows()){
String key = row.getCell("name");
String value = row.getCell("age");
parameters.put(key,value);
}
for (String s: parameters.keySet()){
System.out.println(s+"\t"+parameters.get(s));
} String result = "";//返回的结果
BufferedReader in = null;//读取响应的输入流
StringBuffer sf = new StringBuffer();//存储参数
String params = "";//编码后的参数 try{
if (parameters.size() == 1){
for(String name : parameters.keySet()){
sf.append(name).append("=").append(
java.net.URLEncoder.encode(parameters.get(name),"UTF-8")
);
}
params = sf.toString();
}else{
for(String name : parameters.keySet()){
sf.append(name).append("=").append(
java.net.URLEncoder.encode(parameters.get(name),"UTF-8")
).append("&");
}
String tempParams = sf.toString();
params = tempParams.substring(0,tempParams.length()-1);
System.out.println(params);
} String fullUrl = url + "?" + params;
System.out.println(fullUrl); //创建URL对象
URL connUrl = new URL(fullUrl);
//打开URL链接
HttpURLConnection httpConn = (HttpURLConnection)connUrl.openConnection(); // 设置通用属性
httpConn.setRequestProperty("Accept","*/*");
httpConn.setRequestProperty("Connection","Keep-Alive");
httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); //建立实际链接
httpConn.connect(); //响应头部的获取
Map<String,List<String>> headers = httpConn.getHeaderFields(); System.out.println("==============================");
//遍历头部所有字段
for(String key : headers.keySet()){
System.out.println(key+"\t: \t"+headers.get(key));
} //定义bufferedReader输入流来读取URL的响应,并设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8")); String line = "";//读取返回的内容
while((line = in.readLine()) != null){
result = result+line;
} }catch(Exception e){
e.printStackTrace();
}finally{
try{
if(in != null){
in.close();
}
}catch(IOException ex){
ex.printStackTrace();
}
} System.out.println("*****************************");
System.out.println(result);
System.out.println("==============================");
return result;
} //send post request
@Step("the post method url is <url> and parameters are <parametersTable>")
public static String sendPost(String url,Table parametersTable){
Map<String,String> parameters = new HashMap<>(); for(TableRow row : parametersTable.getTableRows()){
String key = row.getCell("name");
String value = row.getCell("age");
parameters.put(key,value);
}
for (String s: parameters.keySet()){
System.out.println(s+"\t\t"+parameters.get(s));
}
System.out.println("---------------------"); String result = "";
BufferedReader in = null;
PrintWriter out = null;//
StringBuffer sf = new StringBuffer();
String params = ""; try{ if (parameters.size() == 1){
for(String name : parameters.keySet()){
sf.append(name).append("=").append(
java.net.URLEncoder.encode(parameters.get(name),"UTF-8")
);
}
params = sf.toString();
}else{
for(String name : parameters.keySet()){
sf.append(name).append("=").append(
java.net.URLEncoder.encode(parameters.get(name),"UTF-8")
).append("&");
}
String tempParams = sf.toString();
params = tempParams.substring(0,tempParams.length()-1);
} URL connUrl = new URL(url); HttpURLConnection httpConn = (HttpURLConnection)connUrl.openConnection(); httpConn.setRequestProperty("Accept","*/*");
httpConn.setRequestProperty("Connection","Keep-Alive");
httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); //设置post方式
httpConn.setDoInput(true);
httpConn.setDoOutput(true); //获取HttpUrlConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream()); //发送请求参数
out.write(params); //flush(冲洗)输出流中的缓冲
out.flush(); in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8")); String line = "";
while((line = in.readLine()) != null){
result = result+line;
} }catch(Exception e){
e.printStackTrace();
}finally{
try{
if(out != null){
out.close();
}
if(in != null){
in.close();
}
}catch(IOException e){
e.printStackTrace();
}
} System.out.println("*****************************");
System.out.println(result);
System.out.println("============================");
return result;
} }

  2.测试类

  用自动化测试工具gauge进行测试

Use http request for creating user
=====================
Created by KSC on 2/7/2017 This is an executable specification file which follows markdown syntax.
Every heading in this file denotes a scenario. Every bulleted point denotes a step. call on url with method get
---------------- tags: get *the get method url is "http://localhost:8080" and parameters are
|name|age|
|----|---|
|tom|20|
|maike|22| call on url with method post
--------------------------- tags: post *the post method url is "https://www.baidu.com/" and parameters are
|name|age|
|----|---|
|marry|20|
|rose|22|