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

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();
        }
    }

借阅【java后台发起上传文件的post请求(http和https)】



我自己封装的类,通用类
/**
 * 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);
	}*/
	
}
  • 1
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Java后端可以使用HttpClient库来实现Post提交文件流及参数的功能。示例代码如下: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 添加文件流 builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, fileName); // 添加参数 builder.addTextBody("param1", "value1", ContentType.TEXT_PLAIN); builder.addTextBody("param2", "value2", ContentType.TEXT_PLAIN); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); CloseableHttpResponse response = httpClient.execute(httpPost); ``` 其中,`url`是要提交到的服务端地址,`file`是要提交的文件流,`fileName`是文件名。`param1`和`param2`是要提交的参数及其对应的值。 在服务端接收文件流及参数时,可以使用Spring框架的`MultipartFile`来接收文件流,使用`@RequestParam`来接收参数。示例代码如下: ```java @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("param1") String param1, @RequestParam("param2") String param2) throws IOException { byte[] bytes = file.getBytes(); // 处理文件流和参数 return "success"; } ``` 其中,`/upload`是服务端接收请求的地址,`file`是要接收的文件流,`param1`和`param2`是要接收的参数。 注意,在服务端接收参数时,需要根据参数的类型来设置参数的`ContentType`。例如,如果参数是文本类型,则设置为`ContentType.TEXT_PLAIN`。如果参数是JSON类型,则设置为`ContentType.APPLICATION_JSON`。 以上就是Java后端HttpClient Post提交文件流及参数的实现方式。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值