http接⼝实现附件对接1、推送附件 filebody
/**
* 推送附件⽅法
* @param args
*/
public static void main2(String[] args){
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = ateDefault();
// 把⼀个普通参数和⽂件上传给下⾯这个地址是⼀个servlet
HttpPost httpPost = new HttpPost("localhost:8088/api/xfSystemToJsxf/acceptOutSystemUpload");
// 请求头设置token值
httpPost.setHeader("token", "8c17f4d7-c53a-42e3-aa22-8f3f8e41f25e");
StringBody extendId = new StringBody("705d7630-d097-4a4c-806e-61b0cd50ba2f", ate( "text/plain", "utf-8"));
StringBody extendCaseCode = new StringBody("NJ12369", ate(
"text/plain", "utf-8"));
// 相当于<input type="text" name="extendId" value=extendId>
MultipartEntityBuilder meb = ate()
.addPart("extendId", extendId)
.addPart("extendCaseCode", extendCaseCode);
List<FileBody> fileBodyList=new ArrayList<>();
fileBodyList.add(new FileBody(new File("C:\\Users\\wangmq\\Desktop\\附件1.docx")));
fileBodyList.add(new FileBody(new File("C:\\Users\\wangmq\\Desktop\\附件2.doc")));
for(int i=0; i<fileBodyList.size(); i++){
FileBody (i);
// 把⽂件转换成流对象FileBody
StringBody fileName = new Filename(), ate(
"text/plain", "utf-8"));
meb.addPart("fileName"+i, fileName);
meb.addPart("fileBody"+i, fileBody);
}
/
/ setMode(HttpMultipartMode.RFC6532)解决⽂件名中⽂成?的问题
HttpEntity reqEntity = meb.setMode(HttpMultipartMode.RFC6532).build();
httpPost.setEntity(reqEntity);
// 发起请求并返回请求的响应
response = ute(httpPost);
System.out.println("响应状态码==========" + StatusLine());
System.out.println("响应头===========" + LastHeader("fileResult"));
// 获取响应对象
HttpEntity resEntity = Entity();
if (resEntity != null) {
// 打印响应长度
System.out.println("Response content length: " + ContentLength());
// 打印响应内容
System.out.String(resEntity, Charset.forName("UTF-8")));
}
// 销毁
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(response != null){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(httpClient != null){
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、接收推送的附件 filebody
@ResponseBody
@RequestMapping(value = "/acceptJsxfManageFile", method = RequestMethod.POST)
public JsonResult acceptJsxfManageFile(HttpServletRequest request, HttpServletResponse response){
JsonResult jsonResult = SuccessResult();
try {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
// 开始保存附件
String jsxfManageFilePath = ConfigValueByKey("jsxfManageFilePath");
File uploadFile = new File(jsxfManageFilePath);
if (!ists()) {
uploadFile.mkdirs();
}
// 检测是不是存在上传⽂件
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
//指定在内存中缓存数据⼤⼩,单位为byte,这⾥设为50Mb
factory.setSizeThreshold(50*1024*1024);
//设置⼀旦⽂件⼤⼩超过getSizeThreshold()的值时数据存放在硬盘的⽬录
factory.setRepository(new File("C:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// 指定单个上传⽂件的最⼤尺⼨,单位:字节,这⾥设为50Mb
upload.setFileSizeMax(50 * 1024 * 1024);
//指定⼀次上传多个⽂件的总尺⼨,单位:字节,这⾥设为99Mb
upload.setSizeMax(99 * 1024 * 1024);
upload.setHeaderEncoding("UTF-8");
List<FileItem> items = null;
/
/ 解析request请求
items = upload.parseRequest(request);
// 外部系统案件主键id
String extendId = "";
if(items!=null){
//解析表单项⽬
Iterator<FileItem> iter = items.iterator();
// MultipartEntityBuilder对象的addPart设置参数是有序的,就按照设置的先后⾃然顺序排列
// 遍历变化的fileStatus
String fileStatusIter = "";
String fileNameIter = "";
int acceptFileNum = 0;
while (iter.hasNext()) {
FileItem item = ();
//如果是普通表单属性
if (item.isFormField()) {
//相当于input的name属性 <input type="text" name="content">
String name = FieldName();
//input的value属性
String value = String();
if("extendId".equals(name)){
extendId = value;
}
// 设置遍历变化的fileStatus
if(name.indexOf("fileStatus")!=-1){
fileStatusIter = value;
}
// 设置遍历变化的filename
if(name.indexOf("fileName")!=-1){
fileNameIter = value;
}
} else {
// 是⽂件,加⼀层⽂件夹路径,⽂件夹名为外部系统案件主键id
String uploadPathExtendId = jsxfManageFilePath+"\\"+extendId+"\\";
File uploadPathExtendIdDir = new File(uploadPathExtendId);
if(!ists()){
uploadPathExtendIdDir.mkdirs();
}
//属性名
String fieldName = FieldName();
//上传⽂件路径
// String fileName = Name();
String fileName = fileNameIter;
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);// 获得上传⽂件的⽂件名
/
/ ⽂件输出流写到本地硬盘保存
item.write(new File(uploadPathExtendIdDir, fileName));
acceptFileNum ++;
// 插⼊中间库案件和附件的关联信息
if(systemService.addLocaleSurvey(fileStatusIter, extendId, uploadPathExtendId, fileName, ComplainContant.JSXF_MANAGE_FILE)){ jsonResult.setTotal(acceptFileNum);
}
}
}
}
}
}catch (Exception e){
jsonResult.setSuccess(false);
e.printStackTrace();
}finally {
return jsonResult;
}
}
3、j将⾃⼰⽂件打包,供别⼈获取
@ResponseBody
@RequestMapping(value = "takeOutSystemUpload")
public void takeOutSystemUpload(@RequestBody DataSyncParam dataSyncParam, HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
OutputStream out = OutputStream();
ZipOutputStream zos = new ZipOutputStream(out);
// 外部系统案件主键id
String extendId = ExtendId();
try {
if(StringUtils.isNullOrEmpty(extendId)){
response.setStatus(4003);
response.setHeader("fileResult", "error, extendId is null");
}else{
/
/ 根据extendid到⽂件夹,遍历获取要打包的多个⽂件
String filePathNameDir = ConfigValueByKey("outSystemUploadPath")+extendId+"\\";
File[] fileArray = new File(filePathNameDir).listFiles();
if(fileArray == null){
response.setStatus(4004);
response.setHeader("fileResult","error, extendId is invalid");
}else{
int takeFileNum = 0;
for(File file : fileArray){
ZipEntry entry = new Name());
zos.putNextEntry(entry);
byte [] bytes = new byte[1024];
int len;
FileInputStream in = new FileInputStream(file);
while((len = in.read(bytes)) != -1) {
zos.write(bytes, 0, len);
}
takeFileNum++;
zos.closeEntry();
in.close();
}
response.setStatus(200);
response.setHeader("fileResult","success, return "+takeFileNum+" files successfully");
}
}
} catch (Exception e) {
response.setStatus(-1);
e.printStackTrace();
}finally {
if(zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4、获取打包的附件
public static void main4(String[] args){
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
Map<String, String> params = new HashMap<>();
String extendId = "705d7630-d097-4a4c-806e-61b0cd50ba2f";
params.put("extendId", extendId);
//发送http请求,并处理返回的zip包
HttpPost httpPost = new HttpPost("localhost:8088/api/xfSystemToJsxf/takeJsxfManageFile");
httpPost.addHeader("token", "c279adad-0cb0-4d3c-9436-644d513c41fa");
MultipartEntityBuilder builder = ate().setCharset(Charset.forName("utf-8"));
String value = "";
if (params != null) {
for (String key : params.keySet()) {
value = ((key);
if (value == null) value = "";
builder.addTextBody(key, value, ContentType.APPLICATION_JSON);
}
}
HttpEntity multipart = builder.setMode(HttpMultipartMode.RFC6532).build();
httpPost.setEntity(multipart);
Map<String, Object> map = new HashMap<>();
try {
httpClient = ateDefault();
response = ute(httpPost);
String[] statusLineArray = StatusLine().toString().split(" ");
System.out.println("响应状态吗===========" + StatusLine());
System.out.println("响应头===========" + LastHeader("fileResult"));
js获取json的key和valueif("200".equals(statusLineArray[1])){
try {
HttpEntity entity = Entity();//从response⾥获取数据实体
InputStream in = Content();//获取数据流
Charset c = Charset.forName("UTF-8");
ZipInputStream zin = new ZipInputStream(in, c);//封装成zip输⼊流
BufferedOutputStream bos = null;
ZipEntry ze;
//// 加⼀层⽂件夹路径,⽂件夹名为外部系统案件主键id
String path = "C:\\Users\\wangmq\\Desktop\\outSystemManageFile\\"+extendId+"\\"; File filePathDir = new File(path);
if(!ists()){
filePathDir.mkdirs();
}
File file = null;
while((ze = NextEntry()) != null) {//循环zip输⼊流,获取每⼀个⽂件实体
file = new File(path + ze.getName());//⽣成file(如果⽂件路径不存在,先创建) FileOutputStream fos = new FileOutputStream(file);
int len;
byte [] bytes = new byte[2048];
bos = new BufferedOutputStream(fos,2048);
while((len = ad(bytes, 0, 2048)) != -1) {
bos.write(bytes, 0, len);
}
bos.flush();
bos.close();
}
zin.close();//关闭输⼊流
}catch(Exception e){
e.printStackTrace();
} finally {
if (response != null) response.close();
}
}
} catch (IOException e) {
<("获取附件发送异常" + e);
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论