解压压缩包
/**
* 压缩文件解压
* @param zipFilePath
* @return
* @throws Exception
*/
public static List<String> zipUncompress(String zipFilePath) throws Exception {
List<String> targetFilePaths = new ArrayList<String>();
File srcFile = new File(zipFilePath);
// 判断源文件是否存在
if (!srcFile.exists()) {
throw new Exception(srcFile.getPath() + "所指文件不存在");
}
String destDirPath = zipFilePath.replace(".zip", "");
//创建压缩文件对象
ZipFile zipFile = new ZipFile(srcFile);
//开始解压
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
// 如果是文件夹,就创建个文件夹
if (entry.isDirectory()) {
srcFile.mkdirs();
} else {
String targetFilePath = destDirPath + "/" + entry.getName();
// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
File targetFile = new File(targetFilePath);
targetFilePaths.add(targetFilePath);
// 保证这个文件的父文件夹必须要存在
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 将压缩文件内容写入到这个文件中
InputStream is = zipFile.getInputStream(entry);
org.apache.commons.io.FileUtils.copyInputStreamToFile(is,targetFile);
is.close();
}
}
return targetFilePaths;
}
文件下载
@GetMapping("common/downloadFiles")
public void fileDownloadDataQuality(String fileName, String filePath, HttpServletResponse response, HttpServletRequest request)
{
try
{
String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, realFileName);
FileUtils.writeBytes(filePath, response.getOutputStream());
}
catch (Exception e)
{
log.error("下载文件失败", e);
}
}
/**
* 输出指定文件的byte数组
*
* @param filePath 文件路径
* @param os 输出流
* @return
*/
public static void writeBytes(String filePath, OutputStream os) throws IOException
{
FileInputStream fis = null;
try
{
File file = new File(filePath);
if (!file.exists())
{
throw new FileNotFoundException(filePath);
}
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0)
{
os.write(b, 0, length);
}
}
catch (IOException e)
{
throw e;
}
finally
{
IOUtils.close(os);
IOUtils.close(fis);
}
}
dom4j读取并解析文件内容
// 创建SAXReader的对象reader
SAXReader reader = new SAXReader();
for(int i=0;i<filePaths.size();i++){
// 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
Document document = reader.read(new File(filePaths.get(i)));
List<TjCrpt> cript = loadCrptItemXml(document);
resultList.addAll(cript);
}
public List<TjCrpt> loadCrptItemXml(Document document) throws Exception {
List<TjCrpt> crptsList = new ArrayList<TjCrpt>();
// 解析books.xml文件
// 通过document对象获取根节点bookstore
Element node = document.getRootElement();
//List<Element> datas = node.elements("DATAS");
List<Element> crpts = node.elements("TB_TJ_CRPTS");
for(Element itemCrpt:crpts){
TjCrpt tjCrpt = new TjCrpt();
Element crpt = itemCrpt.element("TB_TJ_CRPT");
tjCrpt.setRid(base64DecString(crpt.element("RID")));
。。。。。。
http传输表单文件
public static String postUpToProvince(String url, String unitCode,
String password, String fileName, String filePath){
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = null;
try {
File file = new File(filePath);
HttpPost httpPost = new HttpPost(url);
//String encoding = DatatypeConverter.printBase64Binary("username:password".getBytes("UTF-8")); //username password 自行修改 中间":"不可少
String authStr = "unitCode="+unitCode+":password="+password;
String encoding = DatatypeConverter.printBase64Binary(authStr.getBytes("UTF-8")); //username password 自行修改 中间":"不可少
httpPost.setHeader("Authorization", "Basic " + encoding);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();//binFile参数-服务端通过此参数获取文件
builder.addBinaryBody("dataFile", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流<br> //filename-文件名参数
builder.addTextBody("unitCode", unitCode);
builder.addTextBody("password", password);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
}catch (Exception e) {
e.printStackTrace();
result = "thisSystemError:"+e.toString();
} finally {
try {
httpClient.close();
} catch (IOException e) {
result = "thisSystemError:"+e.toString();
e.printStackTrace();
}
}
return result;
}
form表单中传递普通参数:
List<NameValuePair> list = new LinkedList<>();
list.add( new BasicNameValuePair("pageHelper","1sfsdf" ));
// 使用URL实体转换工具
UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8"); //使用 UrlEncodedFormEntity 来设置 body,消息体内容
httpPost.setEntity(entityParam);
传输x-www-form-urlencoded类型的
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
RestTemplate restTemplate=new RestTemplate();
MultiValueMap<String, String> forms= new LinkedMultiValueMap<String, String>();
forms.put("grant_type", Collections.singletonList("client_credentials"));
forms.put("client_id", Collections.singletonList("1ae5cada-7bcf-45cb-bad0-8942bfb5f9da"));
forms.put("client_secret", Collections.singletonList("09f747e2-33dc-4173-8159-6649291ca594"));
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(forms, headers);
//获取返回数据
String body = restTemplate.postForObject(url, httpEntity, String.class);
System.out.println(body);
Map<String, Object> map = (Map<String, Object>) JSONUtils.parse(body);
其他发送方式
public class RestTemplateUtils {
//private final static Logger logger = LoggerFactory.getLogger(RestTemplateUtils.class);
/**
* 向目的URL发送post请求
* @param url 目的url
* @param params 发送的参数
* @return RestTemplateResultVo
*/
public static RestTemplateAreaResultVo sendPostRequestArea(String url, JSONObject params){
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpMethod method = HttpMethod.POST;
// 以表单的方式提交
headers.setContentType(MediaType.APPLICATION_JSON);
//将请求头部和参数合成一个请求
HttpEntity<JSONObject> requestEntity = new HttpEntity<>(params, headers);
//执行HTTP请求,将返回的结构使用ResultVO类格式化
client.exchange(url, method, requestEntity, RestTemplateAreaResultVo.class);
ResponseEntity<RestTemplateAreaResultVo> response = client.exchange(url, method, requestEntity, RestTemplateAreaResultVo.class);
return response.getBody();
}
public static RestTemplateHospitalResultVo sendPostRequestHospital(String url, JSONObject params){
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpMethod method = HttpMethod.POST;
// 以表单的方式提交
headers.setContentType(MediaType.APPLICATION_JSON);
//将请求头部和参数合成一个请求
HttpEntity<JSONObject> requestEntity = new HttpEntity<>(params, headers);
//执行HTTP请求,将返回的结构使用ResultVO类格式化
client.exchange(url, method, requestEntity, RestTemplateHospitalResultVo.class);
ResponseEntity<RestTemplateHospitalResultVo> response = client.exchange(url, method, requestEntity, RestTemplateHospitalResultVo.class);
return response.getBody();
}
/**
* 向目的URL发送post请求
* 1. 交易数统计、各医院占比统计
* @param url 目的url
* @param params 发送的参数
* @return RestTemplateResultVo
*/
public static RestTemplateAreaResultVo sendPostRequestForResult1(String url, JSONObject params){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<String> requestEntity = new HttpEntity<String>(params.toString(), headers);
// 执行HTTP请求
ResponseEntity<RestTemplateAreaResultVo> exchange = restTemplate.exchange(url, HttpMethod.POST, requestEntity, RestTemplateAreaResultVo.class);
return exchange.getBody();
}
/**
* 向目的URL发送get请求
* @param url 目的url
* @return RestTemplateResultVo
*/
public static RestTemplateAreaResultVo sendGetRequest(String url){
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type","application/json");
HttpEntity<RestTemplateAreaResultVo> jsonObject= client.exchange(url, HttpMethod.GET,new HttpEntity<RestTemplateAreaResultVo>(headers), RestTemplateAreaResultVo.class);
return jsonObject.getBody();
}
/**
* 调用发送记录结果 返回推送结果
* @param encryptStr
* @param props
*/
// public static void sendRecord(String encryptStr, MyProps props){
// String paramStr = RestTemplateUtils.getCipherText(props.getAppid(),props.getAppkey(),encryptStr);
// String url = props.getSendrecordpath()+"?"+paramStr;
// System.out.println("url:"+url);
// RestTemplateResultVo resultVo = RestTemplateUtils.sendGetRequest(url);
// if (resultVo.isSuccess()){
// System.out.println("回发发送成功:"+resultVo.getMsg());
// }else{
// logger.error("回发消息失败:"+resultVo.getMsg());
// }
// }
}