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 结合可以使得文件操作变 ...
随机推荐
- LoadRunner通过webservice协议调用WSDL接口时,返回值不正确
有可能是某些传参空的值导致的. 解决办法:注释掉空值传参.或者将其值转变为true ”ProductIDSpecified=true“,
- 连通数[JSOI2010]-洛谷T4306
咕咕咕 tarjan+拓排应该是正解吧 然而我上去就打了个tarjan和dijkstra (由于我抄题解抄多了,代码能力极差,于是我就gg了) 题解中有大佬直接用dfs过了8个点,再吸口氧就AC了 ( ...
- 拥抱高通的联想,真的能靠5G突围?
编辑 | 于斌 出品 | 于见(mpyujian) 2016年,对于常年自我标榜为"民族企业"的联想来说是品牌口碑的"转折之年".它在这一年的5G信道编码标准方 ...
- PB 数据窗口点击标题不能排序的一个原因
标题必须和数据行名称一致,如 数据行列名为:num ,标题行必须为 num_t 才可以
- 使用URLConnection获取页面返回的xml数据
public static void main(String[] args) throws Exception { String path="http://flash.weather.com ...
- Vue中组件之间的通信方式
vue是数据驱动视图更新的框架, 所以对于vue来说组件间的数据通信非常重要,那么组件之间如何进行数据通信的呢? 本文会介绍组件间通信的8种方式如下图所示, 并介绍在不同的场景下如何选择有效方式实现的 ...
- 关于无线的Idle Timeout和Session Timeout
1.Session Timeout Session Timer的默认值为1800s,也就是30min.Session Timeout:当该计时器超时时,使得客户端强制发生重认证,这个时间是从客户端认证 ...
- Educational Codeforces Round 82 C. Perfect Keyboard
Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him ...
- 虚拟机设置固定IP从而使同一局域网可以访问
没有ifcfg-eth0 时:https://www.cnblogs.com/itboxue/p/11186910.html (1)关机,将网络模式设置成桥接模式 (2)开机 进入 cd /etc/s ...
- Yar并行的RPC框架的简单使用
前言: RPC,就是Remote Procedure Call的简称呀,翻译成中文就是远程过程调用 RPC要解决的两个问题: 解决分布式系统中,服务之间的调用问题. 远程调用时,要能够像本地调用一样方 ...