在做接口自动化测试时,遇到GET方法需要传参,一般如下面例子
httpget.setHeader("User-Agent", "Chrome");
httpget.setHeader("Content-Type", "application/json;charset=UTF-8");
List<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("username", "admin"));
data.add(new BasicNameValuePair("password", "123***"));
data.add(new BasicNameValuePair("type", "login"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(data);
httpget.setEntity(formEntity);
这里对List<NameValuePair>设置GET参数进行封装,例子
调用:
public static String doGet(String url,Map<String,String> params,String token) throws Exception{
// 根据参数,创建访问的地址
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
}
/**
* Description: 封装请求参数
*
* @param params
* @param httpMethod
* @throws UnsupportedEncodingException
*/
public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
throws UnsupportedEncodingException {
// 封装请求参数
if (params != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 设置到请求的http对象中
httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
}
}
这里封装使用的是Map的entrySet遍历。
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
entrySet解释:
entrySet是 java中 键-值 对的集合,Set里面的类型是Map.Entry,一般可以通过map.entrySet()得到。
entrySet实现了Set接口,里面存放的是键值对。一个K对应一个V。
用来遍历map的一种方法。
即通过getKey()得到K,getValue得到V。
参考资料:
Java中Map的 entrySet() 详解以及用法(四种遍历map的方式)
https://blog.csdn.net/wang386476890/article/details/115654635