接口测试中模拟POST请求数据的方法有四种,分别是:表单提交、JSON提交、XML提交、文件上传。
表单提交
表单提交是最常见的POST请求数据方式,它将请求参数以表单的形式提交,请求参数的格式为:key1=value1&key2=value2。
//表单提交 Mapparams = new HashMap<>(); params.put("key1","value1"); params.put("key2","value2"); HttpPost httpPost = new HttpPost("http://www.xxx.com"); List list = new ArrayList<>(); for(String key:params.keySet()){ list.add(new BasicNameValuePair(key,params.get(key))); } httpPost.setEntity(new UrlEncodedFormEntity(list,"utf-8"));
JSON提交
JSON提交是向服务器发送JSON数据,它将请求参数以JSON的形式提交,请求参数的格式为:{"key1":"value1","key2":"value2"}。
//JSON提交 JSONObject jsonObject = new JSONObject(); jsonObject.put("key1","value1"); jsonObject.put("key2","value2"); StringEntity stringEntity = new StringEntity(jsonObject.toString(),"utf-8"); HttpPost httpPost = new HttpPost("http://www.xxx.com"); httpPost.setEntity(stringEntity);
XML提交
XML提交是向服务器发送XML数据,它将请求参数以XML的形式提交,请求参数的格式为:
//XML提交 String xml = "value1 value2 "; StringEntity stringEntity = new StringEntity(xml,"utf-8"); HttpPost httpPost = new HttpPost("http://www.xxx.com"); httpPost.setEntity(stringEntity);
文件上传
文件上传是向服务器发送文件,它将请求参数以文件的形式提交,请求参数的格式为:key1=filename1&key2=filename2。
//文件上传 Mapparams = new HashMap<>(); params.put("key1","filename1"); params.put("key2","filename2"); HttpPost httpPost = new HttpPost("http://www.xxx.com"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for(String key:params.keySet()){ File file = new File(params.get(key)); builder.addBinaryBody(key,file); } HttpEntity entity = builder.build(); httpPost.setEntity(entity);