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

Posted kaschie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    */
    

 

 

以上是关于Java后端 带File文件及其它参数的Post请求的主要内容,如果未能解决你的问题,请参考以下文章

RestTemplate发送带body参数的post请求

上传失败缺少请求参数file

java代码发送post请求,并接收xml文件。。。 发送请求时要带参数

Java前后端分离项目生成二维码链接带中文参数遇到的问题及解决办法

Java前后端分离项目生成二维码链接带中文参数遇到的问题及解决办法

Java前后端分离项目生成二维码链接带中文参数遇到的问题及解决办法