httpclient调用接口
1 public static String sendData(String url,String codeType,Map<String,String> datas,Map<String,File> files){ 2 CloseableHttpClient httpClient = HttpClients.createDefault(); 3 String result = ""; 4 try{ 5 // 接口地址 6 HttpPost httpPost = new HttpPost(url); 7 //以浏览器兼容模式运行,防止文件名乱码。 8 MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 9 10 //普通参数 11 if(datas != null && !datas.isEmpty()){ 12 for (Map.Entry<String, String> entry : datas.entrySet()) { 13 multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue()); 14 } 15 } 16 //文件参数 17 if(files != null && !files.isEmpty()){ 18 for (Map.Entry<String, File> entry : files.entrySet()) { 19 multipartEntityBuilder.addBinaryBody(entry.getKey(), entry.getValue()); 20 } 21 } 22 23 HttpEntity reqEntity = multipartEntityBuilder.build(); 24 25 httpPost.setEntity(reqEntity); 26 // 发起请求 并返回请求的响应 27 CloseableHttpResponse response = httpClient.execute(httpPost); 28 try{ 29 // 获取响应对象 30 int status = response.getStatusLine().getStatusCode(); 31 if(status == HttpStatus.SC_OK){ 32 HttpEntity resEntity = response.getEntity(); 33 if(resEntity != null) { 34 // 响应内容 35 if(codeType==null || codeType==""){ 36 codeType = "UTF-8"; 37 } 38 result = EntityUtils.toString(resEntity,codeType); 39 // 销毁 40 } 41 EntityUtils.consume(resEntity); 42 } 43 }finally{ 44 response.close(); 45 } 46 }catch (Exception e) { 47 e.printStackTrace(); 48 result = ""; 49 }finally{ 50 try { 51 httpClient.close(); 52 } catch (IOException e) { 53 e.printStackTrace(); 54 } 55 } 56 return result; 57 }