使用HttpClient4实现API测试实战(2)——多附件上传
0、特别说明
1、声明:如需转载,请注明来自 http://cgs1999.iteye.com/;
2、阅读本文前建议先阅读下面博客:
使用HttpClient4实现API测试实战(1)
1、引言
API测试过程中,有些API接口可能需要上传附件,而且是多个附件,本文主要是解决API测试过程中的多附件上传问题。
当然,你也可以将本文当作使用HttpClient模拟HTTP实现多附件上传的文章来阅读。
2、更新测试项目
2.1 添加项目依赖
httpmime-4.2.1.jar
public static String doPostUpload(String url, List<BasicNameValuePair> datas, List<String> files) { try { // 组装提交信息 MultipartEntity reqEntity = new MultipartEntity(); for(BasicNameValuePair data : datas) { reqEntity.addPart(data.getName(), new StringBody(data.getValue(), "text/plain", Charset.forName("UTF-8"))); } for(String file : files) { reqEntity.addPart("file", new FileBody(new File(file))); } // 设置提交信息 HttpPost httppost = new HttpPost(url); httppost.setEntity(reqEntity); HttpResponse httpResponse = httpClient.execute(httppost); // 若状态码为200 okif (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 取出回应字串String strResult = EntityUtils.toString(httpResponse.getEntity());System.out.println("doPostJson response[" + url + "]: \n" + strResult);return strResult;} else {System.out.println("doPost Error Response[" + url + "]: \n" + httpResponse.getStatusLine().toString());} } catch (Exception e) {e.printStackTrace();} return null; }
// 发布带附件信息public static boolean uploadMessage(String status, List<String> files) {return uploadMessage(status, null, files);}public static boolean uploadMessage(String status, String groupId, List<String> files) {List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(0);params.add(new BasicNameValuePair("account_token", getToken()));params.add(new BasicNameValuePair("status", status));if(groupId!=null) {params.add(new BasicNameValuePair("group_id", groupId));}String xml = HttpClientUtil.doPostUpload(API_URL + "/messages/upload", params, files);if (!hasText(xml)) {return false;}if (xml.indexOf("errorCode") == -1) {return true;} else {return false;}}
public static void main(String[] argus) {login("chengesheng@gmail.com", "password");List<String> files = new ArrayList<String> (0);files.add("c:\\myimage.jpg");files.add("c:\\dulala.txt");uploadMessage("测试附件和图片上传1", "151", files);}