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 结合可以使得文件操作变 ...
随机推荐
- Postman的使用和测试
1.输入认证的IP,获取headers 2.输入用户名及密码 3.带着headers去访问网址 4.传参
- acm数论之旅--欧拉函数的证明
随笔 - 20 文章 - 0 评论 - 73 ACM数论之旅7---欧拉函数的证明及代码实现(我会证明都是骗人的╮( ̄▽ ̄)╭) https://blog.csdn.net/chen_ze_hua ...
- stopWatch 用法
package com.example.stopwatch; import org.springframework.util.StopWatch; public class TestStopWatch ...
- JAVA(2)之关于类的访问权限控制
类的成员的四种访问权限 private 只能在当前类中访问 无修饰 同一个包中的类都可以访问 protected 同一个包中的类可以访问 不同包中的子类可以访问 public 所有类都可以访问 示例代 ...
- JSP技术(一)
Servlet的两个缺点: 1.首先,写在Servlet中所有的HTML标签必须包含JAVA字符串,使得处理HTTP响应报文工作十分繁琐. 2.所有的文件和HTML标记是硬代码,导致即使是微小变化,也 ...
- Jmeter_请求原件之参数化CSV
1.用途:注册10个账户 2.用CSV 制造数据相对比TEXT更方便 3.创建CSV 文件,注册账户和密码如下 4.Jmeter设置如下 因为是注册10个账户,要运行10次 5.线程组->添加- ...
- 安装pyhanlp
安装pyhanlp pyhanlp是java写的,外层封装了python. 对于新手,在使用的时候稍有难度. 1. 下载源码 https://github.com/hankcs/pyhanlp git ...
- 为什么阿里Java手册推荐慎用 Object 的 clone 方法来拷贝对象
图片若无法显示,可至掘金查看https://juejin.im/post/5d425230f265da039519d248 前言 在阿里Java开发手册中,有这么一条建议:慎用 Object 的 cl ...
- slf4j-api整合maven 工程日志配置文件
springmvc项目 pom.xml: <dependency> <groupId>org.slf4j</groupId> <artifactId>s ...
- BUG搬运工:CSCvp31778-3802 apsw_watchdog: WARNING: System memory is running low
如下bug主要针对Cisco COS AP比如18.28.38... 主要现象: AP上连关联的终端显示的是信号满格,但是无法访问内网,所有的终端都这样,只有重启AP后才可以解决. 频率: 这种现象有 ...