上传文件
public String mediaUploadFile(String url, String filePath, String type) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String accessToken = getAccessToken(false);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("X-Auth0-Token", accessToken);
// 把文件转换成流对象FileBody
FileBody bin = new FileBody(new File(filePath));
StringBody fileType = new StringBody(type, ContentType.create(
"text/plain", Consts.UTF_8));
HttpEntity reqEntity = MultipartEntityBuilder.create()
// 相当于<input type="file" name="file"/>
.addPart("file", bin)
.addPart("type", fileType)
// 相当于<input type="text" name="userName" value=userName>
.build();
httpPost.setEntity(reqEntity);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
if (responseContent.isEmpty()) {
//返回
}
log.debug("\n【请求地址】: {}\n【Token】:{}\n【响应数据】:{}", url, accessToken, responseContent);
return responseContent;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpPost.releaseConnection();
}
throw new RuntimeException("服务端异常");
}
下载文件
public void mediaDownloadFile(String url, String param,HttpServletResponse response) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String accessToken = getAccessToken(false);
HttpGet httpget = new HttpGet(url+"?"+param);
httpget.setHeader("X-Auth0-Token", accessToken);
httpget.setHeader("Content-Type", "application/json;charset=UTF-8");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
HttpResponse execute = httpClient.execute(httpget);
outputStream = response.getOutputStream();
log.debug("\n【请求地址】: {}\n【Token】:{}", url, accessToken);
// 获取响应对象
HttpEntity entity = execute.getEntity();
if (execute.getStatusLine().getStatusCode() != 200) {
log.error(EntityUtils.toString(execute.getEntity(), Consts.UTF_8));
return;
}
response.setContentType(getContentType(url));
// response.setHeader("Content-Disposition", "attachment;filename="
// .concat(String.valueOf(URLEncoder.encode(UUID.randomUUID().toString().replace("-",""), "UTF-8"))));
inputStream = entity.getContent();
//stream 转byte
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
//buff用于存放循环读取的临时数据
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inputStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] bytes = swapStream.toByteArray();
Image img = ImageIO.read(new ByteArrayInputStream(bytes));
// 如果不是图片
if (img == null) {
log.error("文件不存在");
return;
}else {
outputStream.write(bytes);
outputStream.flush();
}
// 销毁
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(inputStream!=null){
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(outputStream!=null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}