http://www.roak.com

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请求的更多相关文章

  1. java中的File文件读写操作

    之前有好几次碰到文件操作方面的问题,大都由于时间太赶而没有好好花时间去细致的研究研究.每次都是在百度或者博客或者论坛里面參照着大牛们写的步骤照搬过来,之后再次碰到又忘记了.刚好今天比較清闲.于是就在网 ...

  2. java学习(九) —— java中的File文件操作及IO流概述

    前言 流是干什么的:为了永久性的保存数据. IO流用来处理设备之间的数据传输(上传和下载文件) java对数据的操作是通过流的方式. java用于操作流的对象都在IO包中. java IO系统的学习, ...

  3. Java IO编程——File文件操作类

    在Java语言里面提供有对于文件操作系统操作的支持,而这个支持就在java.io.File类中进行了定义,也就是说在整个java.io包里面,File类是唯一 一个与文件本身操作(创建.删除.重命名等 ...

  4. java中实现File文件的重命名(renameTo)、将文件移动到其他目录下、文件的复制(copy)、目录和文件的组合(更加灵活方便)

    欢迎加入刚建立的社区:http://t.csdn.cn/Q52km 加入社区的好处: 1.专栏更加明确.便于学习 2.覆盖的知识点更多.便于发散学习 3.大家共同学习进步 3.不定时的发现金红包(不多 ...

  5. java 创建一个File文件对象

    Example10_1.java import java.io.*; public class Example10_1 { public static void main(String args[]) ...

  6. java 编译带包文件

    问题   假设两个文件:     D:\workspace\com\A.java     D:\workspace\com\B.java 两个文件都有:     package com;   如何编译 ...

  7. JMeter学习-027-JMeter参数文件(脚本分发)路径问题:jmeter.threads.JMeterThread: Test failed! java.lang.IllegalArgumentException: File distributed.csv must exist and be readable解决方法

    前些天,在进行分布式参数化测试的时候,出现了如题所示的错误报错信息.此文,针对此做一个简略的重现及分析说明. JMX脚本线程组参数配置如下所示: 参数文件路径配置如下所示: 执行JMX脚本后,服务器对 ...

  8. Java精选笔记_IO流【File(文件)类、遍历目录下的文件、删除文件及目录】

    File(文件)类 File类用于封装一个路径,该路径可以是从系统盘符开始的绝对路径,也可以是相对于当前目录而言的相对路径 File类内部封装的路径可以指向一个文件,也可以指向一个目录,在使用File ...

  9. Java7 新特性 —— java.nio.file 文件操作

    本文部分摘自 On Java 8 自 Java7 开始,Java 终于简化了文件读写的基本操作,新增了 java.nio.file 库,通过与 Java8 新增的 stream 结合可以使得文件操作变 ...

随机推荐

  1. 激活4500-X RTU license

    1.查看设备license Switch#sho version Cisco IOS Software, IOS-XE Software, Catalyst 4500 L3 Switch Softwa ...

  2. js将相除结果百分比 ,四舍五入函数 toFixed()

    function percentNum(num, num2) { return (Math.round(num / num2 * 10000) / 100.00 + "%"); } ...

  3. linux +jenkins +python 集成测试

    1.jenkin安装部署 2.git 安装 3.git server 配置 4.contab

  4. CSS-禁止文本被选中

    pc端: .not-select{ -moz-user-select:none; /*火狐*/ -webkit-user-select:none; /*webkit浏览器*/ -ms-user-sel ...

  5. Django 单元测试笔记

    引言 关于单元测试的基本知识这里不再讲述,简单一句话:单元测试是用一段代码去测试另一段代码.最常用的框架是unittest,这是python的单元测试框架,而django单元测试框架test.Test ...

  6. ASP.NET Core搭建多层网站架构【7-使用NLog日志记录器】

    2020/01/29, ASP.NET Core 3.1, VS2019, NLog.Web.AspNetCore 4.9.0 摘要:基于ASP.NET Core 3.1 WebApi搭建后端多层网站 ...

  7. idea如何提取变量(拆分变量赋值和声明)

    需求描述: 我们时常遇到某个在某个局部作用域声明的变量,想要用在另一个地方,此时就需要在作用域外部声明变量,在作用域中给变量赋值. 在eclipse中这个功能和提取变量在一起,我们可以方便的拆分变量的 ...

  8. 无刷新的批量图片上传插件.NET版

    啥都不说,先上效果图: 这是一个网上的第三方组件,原版是php的,我用.NET重写了图片上传的处理,下面贴上代码 using System; using System.Collections.Gene ...

  9. MySQL 将字符串转换为数字

    转载自:https://www.cnblogs.com/xiaoleiel/p/8316508.html 在操作mysql时,经常需要将字符转换成数字,这一步虽然简单,但不常用的话也很容易忘记,现将在 ...

  10. idea中springboot静态资源及页面跳转问题

    1,静态资源放在resources/static下,html页面放在resources/templates下 2,在html中引入静态资源时,不用带static(对于路径来说是透明的) 3, 配置ht ...