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("https://testzoms.txffp.com/pcs/app/common/checkInvoice");
            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);
    }*/

}
 

原文地址:https://www.cnblogs.com/kaschie/p/11423195.html

时间: 2024-08-01 11:01:24

Java后端 带File文件及其它参数的Post请求的相关文章

java中的File文件读写操作

之前有好几次碰到文件操作方面的问题,大都因为时间太赶而没有好好花时间去仔细的研究研究,每次都是在百度或者博客或者论坛里面参照着大牛们写的步骤照搬过来,之后再次碰到又忘记了,刚好今天比较清闲,于是就在网上找了找Java常用的file文件操作方面的资料.之后加以一番整理,现分享给大家. 直接上源码吧. package com.file; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundEx

java 创建一个File文件对象

Example10_1.java import java.io.*; public class Example10_1 { public static void main(String args[]) { File f = new File("C:\\ch10","Example10_1.java"); System.out.println(f.getName()+"是可读的吗:"+f.canRead()); System.out.println

Java代码调用Shell脚本并传入参数实现DB2数据库表导出到文件

本文通过Java代码调用Shell脚本并传入参数实现DB2数据库表导出到文件,代码如下: import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.util.HashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import

Java file文件的写入和读取

File文件的写入 一.FileWriter 和BufferedWriter 结合写入文件 FileWriter是字符流写入字符到文件.默认情况下,它会使用新的内容代替文件原有的所有内容,但是,当指定一个true值作为FileWriter构造函数的第二个参数,它会保留现有的内容,并追加新内容在文件的末尾. BufferedWriter:缓冲字符,是一个字符流类来处理字符数据.不同于字节流(数据转换成字节FileOutPutStream),可以直接写字符串.数组或字符数据保存到文件. 默认情况,替

springMVC file文件上传及参数接收

springMvc文件上传,首先两个基础, 1.form表单属性中加上enctype="multipart/form-data" 强调:form表单的<form method="post" ...,method必须有,我这里是用的是post,至于get行不行没试过,没有method="post"也会报不是multipart请求的错误. 2.配置文件中配置MultipartResolver 文件超出限制会在进入controller前抛出异常,

Java 自带MD5 校验文件

http://www.iteye.com/topic/1127319 前天第一次发表博客到论坛,关于Java文件监控一文,帖子地址在:http://www.iteye.com/topic/1127281 评论的朋友很多,下载代码的朋友很不少,感谢在论坛上看我帖子的朋友,还有回复评论的朋友,给我提供建议的朋友. 从这些建议中,虽然语言简短,但是却有的是一语中的,这里说一下一下关于帖子的代码中HashFile中的MD5文件校验算法, 该算法是使用Java自带的MessageDigest类,测试结果,

java File文件操作共用方法整理

package org.jelly.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.i

Java流(Stream)、文件(File)和IO

Java流(Stream).文件(File)和IO Java.io包几乎包含了所有操作输入.输出需要的类.所有这些流类代表了输入源和输出目标. Java.io包中的流支持很多种格式,比如:基本类型.对象.本地化字符集等等. 一个流可以理解为一个数据的序列.输入流表示从一个源读取数据,输出流表示向一个目标写数据. Java为I/O提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中. 但本节讲述最基本的和流与I/O相关的功能.我们将通过一个个例子来学习这些功能. 读取控制台输入 Jav

Java笔记:Java 流(Stream)、文件(File)和IO

更新时间:2018-1-7 12:27:21 更多请查看在线文集:http://android.52fhy.com/java/index.html java.io 包几乎包含了所有操作输入.输出需要的类.所有这些流类代表了输入源和输出目标. 输入输出流 简介 一个流被定义为一个数据序列.输入流用于从源读取数据,输出流用于向目标写数据. 下图是一个描述输入流和输出流的类层次图: 在java.io包中操作文件内容的主要有两大类:字节流.字符流,两类都分为输入和输出操作. 在字节流中输出数据主要是使用