TestNG-get请求

主类

//https请求
public class httpsTest extends TestBase {

HttpUtil aHttpUtil = new HttpUtil();

// 变量一般统一放前面
String hosts = "";
String url = "";
String env = "";
String body = "";
String responseData = "";

/*
* 1,@Test 使用testNG注释解使用其框架 2,使用dataProvider 注解来读取csv文件内容(测试用例)
* 3,测试的方法名称以Test结尾 , 方法的参数名称及其位置要和csv文件内容一致
*/

@Test(dataProvider = "CsvDataProvider", dataProviderClass = CsvDataProvider.class)
public void httpsTest(String key, String env, int value) throws IOException, JSONException {

hosts = ConfigModel.host;
url = hosts + "/get?";

// 通过key来控制对应的用例是否执行
if (Integer.parseInt(key) == 1) {

// 请求参数
body = env + "=" + value;
System.out.println("body is"+body);
//getHttpResponseByGet、getHttpRespnseByPost,通过get、post方法得到响应数据
responseData = aHttpUtil.getHttpResponseByGet(url+body);
System.out.println(url+body);
//转成Json对象
JSONObject ajson = new JSONObject(responseData);
//通过key(header)得到value(String)
String headers = ajson.getString("headers");
System.out.println("headers: " + headers);
System.out.println("response is " + responseData);

}
}

}

非主类:getHttpResponseByGet请求

public String getHttpResponseByGet(String url) {
String s = null;
InputStream is = null;
ByteArrayOutputStream out = null;
HttpGet method = null;
DefaultHttpClient hc = new DefaultHttpClient();
hc.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
try {
//url赋给HttpGet
method = new HttpGet(url);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
HttpResponse response = hc.execute(method);
//返回状态码和错误信息
if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
System.err.println("Method failed: " + response.getStatusLine());
}
//返回响应结果
is = response.getEntity().getContent();
out = new ByteArrayOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
s = buffer.toString();

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}

if (out != null) {
out.close();
}

if (method != null) {
method.releaseConnection();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return s;
}

原文地址:https://www.cnblogs.com/zj1234/p/8722591.html