HttpClient下载Excel获取流数据
本篇文章处理的业务场景是通过java代码调用下载excel的链接,然后根据返回的流,解析获取流里的数据,也就是下载的excel数据(其他类型文件思路一致)。调用http链接用的是httpclient包,解析excel用的是poi。
1.导入需要依赖包
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<!-- poi 解析excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.10-FINAL</version>
</dependency>
2.获取流
测试
@Test
public void test1() throws Exception {
String url = "你要下载excel的url";
String cookie = "token";
HttpEntity httpEntity = excelDownload(url, null);
// writeToExcel(httpEntity,"/Users/jeckwu/Desktop/test/1.xlsx");
printInExcelData(httpEntity,"/Users/jeckwu/Desktop/test/1.xlsx");
System.out.println(httpEntity);
}
这里是通过get方式,参数可自行拼接,然后获取链接返回的数据。最好能在像postman这样的软件测试通,看下请求链接和参数有没有问题!
/**
* @Param url 请求下载地址
* */
public HttpEntity excelDownload(String url, String accessToken){
HttpEntity entity = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
// httpGet.setHeader("Content-Type","application/json;charset=UTF-8");
httpGet.setHeader("cookie",accessToken);
HttpResponse response = httpClient.execute(httpGet);
entity = response.getEntity();
}catch (Exception e){
e.printStackTrace();
}
return entity;
}
3.解析数据
解析流,打印流中的数据。其他类型文件都可。
/**
* @Param entity 请求返回内容
* */
public void printInExcelData(HttpEntity entity)throws Exception{
try{
byte[] bytes = EntityUtils.toByteArray(entity);
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
XSSFWorkbook xssfSheets = new XSSFWorkbook(byteInputStream);
XSSFSheet sheetAt = xssfSheets.getSheetAt(0);
List<String> titleList= new ArrayList<>();
for (Cell cell : sheetAt.getRow(0)) {
titleList.add(cell.getStringCellValue());
}
XSSFRow titleRow = sheetAt.getRow(0);
List<Map<String,String>> mapList = new ArrayList<>();
for (int i = 1; i < sheetAt.getLastRowNum(); i++) {
Map<String,String> stringMap = new HashMap<>();
for (int i1 = 0; i1 < sheetAt.getRow(i).getLastCellNum(); i1++) {
stringMap.put(titleList.get(i1),sheetAt.getRow(i).getCell(i1).getStringCellValue());
}
mapList.add(stringMap);
}
log.info("size:{}",mapList.size());
log.info("data:{}",JSON.toJSONString(mapList));
}catch (Exception e){
e.printStackTrace();
}
}
最后打印数据