博客
关于我
java发送post请求,使用multipart/form-data的方式传递参数,可实现服务器间文件上传功能(转)
阅读量:432 次
发布时间:2019-03-06

本文共 4943 字,大约阅读时间需要 16 分钟。

public static void testUploadImage() {    String url = "http://xxxtest/Api/testUploadModelBaking";    String fileName = "e:/username/textures/antimap_0017.png";        // 创建请求参数    Map
textMap = new HashMap<>(); textMap.put("name", "testname"); textMap.put("type", "2"); // 文件参数 Map
fileMap = new HashMap<>(); fileMap.put("upfile", fileName); // 设置内容类型 String contentType = ""; // 上传文件 String ret = formUpload(url, textMap, fileMap, contentType); System.out.println(ret);}
public static String formUpload(String urlStr, Map
textMap, Map
fileMap, String contentType) { String res = ""; HttpURLConnection conn = null; String BOUNDARY = "---------------------------123821742118716"; try { URL url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(30000); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream()); // 处理文本参数 if (!textMap.isEmpty()) { StringBuffer strBuf = new StringBuffer(); for (Map.Entry
entry : textMap.entrySet()) { String inputName = entry.getKey(); String inputValue = entry.getValue(); if (inputValue == null) continue; strBuf.append("--").append(BOUNDARY).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"").append(inputName).append("\"").append("\r\n\r\n"); strBuf.append(inputValue); } out.write(strBuf.toString().getBytes()); } // 处理文件参数 if (!fileMap.isEmpty()) { for (Map.Entry
entry : fileMap.entrySet()) { String inputName = entry.getKey(); String inputValue = entry.getValue(); if (inputValue == null) continue; File file = new File(inputValue); String filename = file.getName(); // 设置内容类型 if (!"".equals(contentType)) { if (filename.endsWith(".png")) { contentType = "image/png"; } else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) { contentType = "image/jpeg"; } else if (filename.endsWith(".gif")) { contentType = "image/gif"; } else if (filename.endsWith(".ico")) { contentType = "image/x-icon"; } } if ("".equals(contentType)) { contentType = "application/octet-stream"; } StringBuffer strBuf = new StringBuffer(); strBuf.append("--").append(BOUNDARY).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"").append(inputName).append("; filename=\"").append(filename).append("\"").append("\r\n"); strBuf.append("Content-Type: ").append(contentType).append("\r\n\r\n"); out.write(strBuf.toString().getBytes()); DataInputStream in = new DataInputStream(new FileInputStream(file)); byte[] buffer = new byte[1024]; while ((bytes = in.read(buffer)) != -1) { out.write(buffer, 0, bytes); } in.close(); } } // 结束分隔符 byte[] endData = ("--" + BOUNDARY + "--\r\n").getBytes(); out.write(endData); out.flush(); out.close(); // 读取返回数据 StringBuffer strBuf = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { strBuf.append(line).append("\n"); } res = strBuf.toString(); reader.close(); reader = null; } catch (Exception e) { System.out.println("发送POST请求出错:" + urlStr); e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); conn = null; } } return res;}

代码解释

  • testUploadImage 方法:这是一个用于测试上传图片功能的方法,主要用于发送POST请求上传文件。
  • formUpload 方法:这是一个通用的文件上传方法,接收URL、文本参数、文件参数以及内容类型。
  • 请求参数处理:将文本参数转换为form-data格式,包含Content-Disposition和内容。
  • 文件参数处理:根据文件名设置默认内容类型(如PNG、JPEG等),然后将文件内容添加到请求中。
  • 分隔符处理:使用boundary字符串将请求参数和文件内容分隔开,然后发送请求。
  • 返回数据处理:读取服务器返回的数据并输出结果。

转载地址:http://pxbyz.baihongyu.com/

你可能感兴趣的文章
Nginx配置ssl实现https
查看>>
Nginx配置TCP代理指南
查看>>
Nginx配置——不记录指定文件类型日志
查看>>
nginx配置一、二级域名、多域名对应(api接口、前端网站、后台管理网站)
查看>>
Nginx配置代理解决本地html进行ajax请求接口跨域问题
查看>>
nginx配置全解
查看>>
Nginx配置参数中文说明
查看>>
nginx配置域名和ip同时访问、开放多端口
查看>>
Nginx配置好ssl,但$_SERVER[‘HTTPS‘]取不到值
查看>>
Nginx配置如何一键生成
查看>>
Nginx配置实例-负载均衡实例:平均访问多台服务器
查看>>
Nginx配置文件nginx.conf中文详解(总结)
查看>>
Nginx配置负载均衡到后台网关集群
查看>>
ngrok | 内网穿透,支持 HTTPS、国内访问、静态域名
查看>>
NHibernate学习[1]
查看>>
NHibernate异常:No persister for的解决办法
查看>>
NIFI1.21.0_Mysql到Mysql增量CDC同步中_日期类型_以及null数据同步处理补充---大数据之Nifi工作笔记0057
查看>>
NIFI1.21.0_NIFI和hadoop蹦了_200G集群磁盘又满了_Jps看不到进程了_Unable to write in /tmp. Aborting----大数据之Nifi工作笔记0052
查看>>
NIFI1.21.0通过Postgresql11的CDC逻辑复制槽实现_指定表多表增量同步_增删改数据分发及删除数据实时同步_通过分页解决变更记录过大问题_02----大数据之Nifi工作笔记0054
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_根据binlog实现数据实时delete同步_实际操作04---大数据之Nifi工作笔记0043
查看>>