使用HttpClient4实现API测试实战(2)——多附件上传
编程技术  /  houtizong 发布于 3年前   60
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("[email protected]", "password");List<String> files = new ArrayList<String> (0);files.add("c:\\myimage.jpg");files.add("c:\\dulala.txt");uploadMessage("测试附件和图片上传1", "151", files);}
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接