Java后端 带File文件及其它参数的Post请求
Java 带File文件及其它参数的Post请求 对于文件上传,客户端通常就是页面,在前端web页面里实现上传文件不是什么难事,写个form,加上enctype = “multipart/form-data”,在写个接收的就可以了,没什么难的。 如果要用java.net.HttpURLConnection,java后台来实现文件上传,还真有点搞头,实现思路和具体步骤就是模拟页面的请求,页面发出的格式如下: -----------------------------7da2e536604c8 Content-Disposition: form-data; name=“luid” 123 -----------------------------7da2e536604c8 Content-Disposition: form-data; name=“file1”; filename=“D:\haha.txt” Content-Type: text/plain haha hahaha -----------------------------7da2e536604c8 Content-Disposition: form-data; name=“file”; filename=“D:\huhu.png” Content-Type: application/octet-stream 这里是图片的二进制数据 -----------------------------7da2e536604c8–
demo代码只有两个参数,一个File,一个String ———————————————— 版权声明:本文为CSDN博主「jianbin.huang」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qq_17782389/article/details/91519554
public static void sendPostWithFile(String filePath) { DataOutputStream out = null; final String newLine = "\r\n"; final String prefix = "--"; try { URL url = new URL("https://ws-di1.sit.cmrh.com/aiisp/v1/mixedInvoiceFileOCR"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); String BOUNDARY = "-------7da2e536604c8"; conn.setRequestMethod("POST"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); out = new DataOutputStream(conn.getOutputStream()); // 添加参数file File file = new File(filePath); StringBuilder sb1 = new StringBuilder(); sb1.append(prefix); sb1.append(BOUNDARY); sb1.append(newLine); sb1.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"" + newLine); sb1.append("Content-Type:application/octet-stream"); sb1.append(newLine); sb1.append(newLine); out.write(sb1.toString().getBytes()); DataInputStream in = new DataInputStream(new FileInputStream(file)); byte[] bufferOut = new byte[1024]; int bytes = 0; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write(newLine.getBytes()); in.close(); // 添加参数sysName StringBuilder sb = new StringBuilder(); sb.append(prefix); sb.append(BOUNDARY); sb.append(newLine); sb.append("Content-Disposition: form-data;name=\"sysName\""); sb.append(newLine); sb.append(newLine); sb.append("test"); out.write(sb.toString().getBytes()); // 添加参数returnImage StringBuilder sb2 = new StringBuilder(); sb2.append(newLine); sb2.append(prefix); sb2.append(BOUNDARY); sb2.append(newLine); sb2.append("Content-Disposition: form-data;name=\"returnImage\""); sb2.append(newLine); sb2.append(newLine); sb2.append("false"); out.write(sb2.toString().getBytes()); byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); // 写上结尾标识 out.write(end_data); out.flush(); out.close(); // 定义BufferedReader输入流来读取URL的响应 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (Exception e) { System.out.println("发送POST请求出现异常!" + e); e.printStackTrace(); } } ————————
/** * post请求 不带file * 参数使用 * JSONObject jp = new JSONObject(); * String param = jp.toJSONString() */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // URL realUrl = new URL("http://www.roak.com"); URLConnection conn = realUrl.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); out = new PrintWriter(conn.getOutputStream()); out.print(param); out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; // System.out.println(result); } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; }
/** * post请求 带file,map是其余参数 */ public static JSONObject sendPostWithFile(MultipartFile file, HashMap<String, Object> map) { DataOutputStream out = null; DataInputStream in = null; final String newLine = "\r\n"; final String prefix = "--"; JSONObject json = null; PropUtils propUtils = new PropUtils("cfg.properties"); try { String fileOCRUrl = propUtils.getProp("fileOCRUrl"); URL url = new URL(fileOCRUrl); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); String BOUNDARY = "-------KingKe0520a"; conn.setRequestMethod("POST"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); out = new DataOutputStream(conn.getOutputStream()); // 添加参数file // File file = new File(filePath); StringBuilder sb1 = new StringBuilder(); sb1.append(prefix); sb1.append(BOUNDARY); sb1.append(newLine); sb1.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"" + newLine); sb1.append("Content-Type:application/octet-stream"); sb1.append(newLine); sb1.append(newLine); out.write(sb1.toString().getBytes()); // in = new DataInputStream(new FileInputStream(file)); in = new DataInputStream(file.getInputStream()); byte[] bufferOut = new byte[1024]; int bytes = 0; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write(newLine.getBytes()); StringBuilder sb = new StringBuilder(); int k = 1; for (String key : map.keySet()) { if (k != 1) { sb.append(newLine); } sb.append(prefix); sb.append(BOUNDARY); sb.append(newLine); sb.append("Content-Disposition: form-data;name=" + key + ""); sb.append(newLine); sb.append(newLine); sb.append(map.get(key)); out.write(sb.toString().getBytes()); sb.delete(0, sb.length()); k++; } // 添加参数sysName /*StringBuilder sb = new StringBuilder(); sb.append(prefix); sb.append(BOUNDARY); sb.append(newLine); sb.append("Content-Disposition: form-data;name=\"sysName\""); sb.append(newLine); sb.append(newLine); sb.append("test"); out.write(sb.toString().getBytes());*/ // 添加参数returnImage /*StringBuilder sb2 = new StringBuilder(); sb2.append(newLine); sb2.append(prefix); sb2.append(BOUNDARY); sb2.append(newLine); sb2.append("Content-Disposition: form-data;name=\"returnImage\""); sb2.append(newLine); sb2.append(newLine); sb2.append("false"); out.write(sb2.toString().getBytes());*/ byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); out.write(end_data); out.flush(); // 定义BufferedReader输入流来读取URL的响应 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; StringBuffer resultStr = new StringBuffer(); while ((line = reader.readLine()) != null) { resultStr.append(line); } json = (JSONObject)JSONObject.parse(resultStr.toString()); } catch (Exception e) { System.out.println("发送POST请求出现异常!" + e); e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } return json; }
/** * 配置文件通用类 * 用法:实例化后直接调用getProp() * new PropUtils(filePath)传入文件路径,resources下面的部分路径 * @author jianbin */ public class PropUtils { private Properties properties; public PropUtils(String propertisFile) { InputStream in = null; try { properties = new Properties(); in = PropUtils.class.getResourceAsStream("/"+propertisFile); properties.load(in); } catch (IOException e) { e.printStackTrace(); } } public String getProp(String key){ return properties.getProperty(key); } /*public static void main(String[] args) { PropUtils propUtils = new PropUtils("cfg.properties"); String str = propUtils.getProp("jobStatus.3"); System.out.println(str); }*/ }
Java后端 带File文件及其它参数的Post请求的更多相关文章
- java中的File文件读写操作
之前有好几次碰到文件操作方面的问题,大都由于时间太赶而没有好好花时间去细致的研究研究.每次都是在百度或者博客或者论坛里面參照着大牛们写的步骤照搬过来,之后再次碰到又忘记了.刚好今天比較清闲.于是就在网 ...
- java学习(九) —— java中的File文件操作及IO流概述
前言 流是干什么的:为了永久性的保存数据. IO流用来处理设备之间的数据传输(上传和下载文件) java对数据的操作是通过流的方式. java用于操作流的对象都在IO包中. java IO系统的学习, ...
- Java IO编程——File文件操作类
在Java语言里面提供有对于文件操作系统操作的支持,而这个支持就在java.io.File类中进行了定义,也就是说在整个java.io包里面,File类是唯一 一个与文件本身操作(创建.删除.重命名等 ...
- java中实现File文件的重命名(renameTo)、将文件移动到其他目录下、文件的复制(copy)、目录和文件的组合(更加灵活方便)
欢迎加入刚建立的社区:http://t.csdn.cn/Q52km 加入社区的好处: 1.专栏更加明确.便于学习 2.覆盖的知识点更多.便于发散学习 3.大家共同学习进步 3.不定时的发现金红包(不多 ...
- java 创建一个File文件对象
Example10_1.java import java.io.*; public class Example10_1 { public static void main(String args[]) ...
- java 编译带包文件
问题 假设两个文件: D:\workspace\com\A.java D:\workspace\com\B.java 两个文件都有: package com; 如何编译 ...
- JMeter学习-027-JMeter参数文件(脚本分发)路径问题:jmeter.threads.JMeterThread: Test failed! java.lang.IllegalArgumentException: File distributed.csv must exist and be readable解决方法
前些天,在进行分布式参数化测试的时候,出现了如题所示的错误报错信息.此文,针对此做一个简略的重现及分析说明. JMX脚本线程组参数配置如下所示: 参数文件路径配置如下所示: 执行JMX脚本后,服务器对 ...
- Java精选笔记_IO流【File(文件)类、遍历目录下的文件、删除文件及目录】
File(文件)类 File类用于封装一个路径,该路径可以是从系统盘符开始的绝对路径,也可以是相对于当前目录而言的相对路径 File类内部封装的路径可以指向一个文件,也可以指向一个目录,在使用File ...
- Java7 新特性 —— java.nio.file 文件操作
本文部分摘自 On Java 8 自 Java7 开始,Java 终于简化了文件读写的基本操作,新增了 java.nio.file 库,通过与 Java8 新增的 stream 结合可以使得文件操作变 ...
随机推荐
- Springmvc-crud-03(静态资源错误)
错误描述:静态资源加载失败 原因:spring会拦截静态资源 解决办法: <!-- 配置spring支持静态资源请求 --> <mvc:default-servlet-handler ...
- 创业学习---《如何展开竞争情报调研》--D-1.调研模块---HHR计划---以太一堂
第一:<开始学习> 1,投资人看人标准:人品好:创业热情:学习能力. 2,思考题:请你预判一个最靠谱的方向来创业,你会怎么调研呢? 3,预热思考题: (1)在这个赛道,究竟有哪些重要竞争对 ...
- Reverse-Encrypted-Shell-via-Openssl
目录 0x01 简介 0x02 使用openssl反弹加密shell 0x01 简介 使用常规NC或者其他常规的方法反弹shell,由于流量都是明文的,很容易被网络防御设备检测到,因此需要对传输内容进 ...
- wordpress 上传图片出现权限或者http错误
首先上传图片的时候出现了 5.jpg 无法建立目录“wp-content/uploads”/2018/07.有没有上级目录的写权限? 然后啊,找方法啊 1.把var/www/wp-content/up ...
- Linux创建连接命令 ln -s创建软连接
ln -s 是linux中一个非常重要命令,一定要熟悉.它的功能是为某一个文件在另外一个位置建立一个同不的链接,这个命令最常用的参数是-s, 具体用法是:ln -s 源文件 目标文件. 当 我们需要在 ...
- 吴裕雄 python 机器学习——模型选择参数优化随机搜索寻优RandomizedSearchCV模型
import scipy from sklearn.datasets import load_digits from sklearn.metrics import classification_rep ...
- EVE上传Dynamips、IOL和QEMU镜像
1.镜像保存目录: /opt/unetlab/addons ---/dynamips Dynamips镜像保存目录 ---/iol IOL镜像保存目录(运行IOU的镜像 ...
- C语言-switch语句的使用。对文件的输出处理。for循环和if的结合使用。
//函数fun功能:统计字符串中各元音字母的个数,注意:不区分大小写. //重难点:switch语句的使用. #include <stdlib.h> #include <conio. ...
- .NET Core快速入门教程 4、使用VS Code进行C#代码调试的技巧
一.前言 什么是代码调试? 通过调试可以让我们了解代码运行过程中的代码执行信息,比如变量的值等等.通常调试代码是为了方便我们发现代码中的bug. 本篇开发环境 1.操作系统: Windows 10 X ...
- springboot:配置多个数据源
参考:还未整理 https://www.cnblogs.com/carrychan/p/9401471.html https://www.cnblogs.com/lijianda/p/11022892 ...