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-07(springmvc标签错误)
错误:springmvc标签错误 原因:1.在springmvc中的form标签中没有绑定modelAttribute属性 2.必须要获取到参数(可以创建map对象,进行存储参数,再用modelAtt ...
- 关于宽搜BFS广度优先搜索的那点事
以前一直知道深搜是一个递归栈,广搜是队列,FIFO先进先出LILO后进后出啥的.DFS是以深度作为第一关键词,即当碰到岔道口时总是先选择其中的一条岔路前进,而不管其他岔路,直到碰到死胡同时才返回岔道口 ...
- 你了解真正的 restful API 吗?
本文原创地址,博客:https://jsbintask.cn/2019/03/20/api/restful-api-best-practices/(食用效果最佳),转载请注明出处! 前言 在以前,一个 ...
- PHP转换oracle数据库的date类型
今天圣诞节啊,圣诞节快乐啊! 最近遇到一个很纠结的事,就是我在plsql里面查的是这样的,很正常, 但是我用程序查出来就是这样的,啊啊啊,真是崩溃啊 但是我传数据需要上面那种格式,而且我对oracle ...
- Android学习05
AlertDialog(对话框) 它也是其他 Dialog的的父类!比如ProgressDialog,TimePickerDialog等,而AlertDialog的父类是:Dialog! AlertD ...
- 公用技术——面向对象领域——UML图——《The Unified Modeling Language User Guide》V2读书笔记——第一章节(建模的意义)
第一章节到第三章节介绍UML的基本概念.第一章节主要介绍了UML语言的历史,介绍了建模的重要性(狗窝,房子,大厦),介绍了UML要实现哪些目标,在最后介绍了在使用UML语言时应该遵循的一些原则或者是规 ...
- Typora自动生成标题编号
1.要实现的效果 按照markdown语法输入 # 一级标题后,自动生成前面的编号 2.配置方法 2.1.进入目录 2.2.创建文件 2.3.编辑文件 base.user.css /** initi ...
- C++文件写入,读出函数ofstream,ifstream的使用方法
ofstream是从内存到硬盘,ifstream是从硬盘到内存,其实所谓的流缓冲就是内存空间. 1.插入器(<<) 向流输出数据.比如说系统有一个默认的标准输出流(cout),一般情况下 ...
- python requests.request 和session.request区别究竟在哪里
import requests hd={"X-auth":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzeXN0ZW0iLCJBUEkiOiIvdW ...
- 安装完 Ubuntu 16.04.1,重启出现[sda] Assuming drive cache: write through的问题
重装了一下ubuntu,安装成功后重启出现了这个问题 刚开始以为是重启慢,就没在意这么多,可是我等了半个小时,(我特么的真闲,其实是忙别的忘了),还不行,咦,然后我就去找了找问题,哈哈哈哈 看图说话, ...