jinlin
2025-03-21 77d58298d00c11ade8862ca8acb0fdef5a45322e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package com.example.client.utils;
 
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import java.util.Map;
 
/**
 * Http 请求工具类
 * @Author: CcchenCoco
 * @Version: V1.0 HttpUtils, 2021/10/15 15:45
 **/
@Slf4j
public class HttpUtils {
 
    /**
     * 上传文件(多文件)
     * @Author: CcchenCoco
     * @Date: 2022/2/22 17:19
     * @Param:
     **/
 
    public static String GetFileAndObj(String url, Map<String, Object> requestParams) throws Exception {
 
        return HttpUtil.get(url, requestParams);
    }
 
    public static String postFileAndObj(String url,  File[] files, Map<String, Object> requestParams) throws Exception {
        return postFileAndObj(url, files, requestParams, "POST");
    }
 
    public static String postFileAndObj(String url, File[] files, Map<String, Object> requestParams, String action) throws Exception {
 
        BufferedReader responseReader = null;
        OutputStream dos= null;
        String BOUNDARY = "------------------------------fbe188897ec8";
 
        try {
            //建立连接
            URL reqUrl = new URL(url);
            HttpURLConnection httpConn = (HttpURLConnection) reqUrl.openConnection();
            //设置参数
            httpConn.setDoOutput(true);   //需要输出
            httpConn.setDoInput(true);   //需要输入
            httpConn.setUseCaches(false);  //不允许缓存
            httpConn.setRequestMethod(action);   //设置POST方式连接
            httpConn.setRequestProperty("Connection", "Keep-Alive");    // 设置字符编码连接参数
            httpConn.setRequestProperty("Charset", "UTF-8");    // 设置字符编码
            httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);   // 设置请求内容类型
            httpConn.setConnectTimeout(600000);
            httpConn.setReadTimeout(600000);
 
            //连接,也可以不用明文connect,使用下面的httpConn.getOutputStream()会自动connect
            httpConn.connect();
            //建立输入流,向指向的URL传入参数
            dos = httpConn.getOutputStream();
 
            StringBuffer strBuf = new StringBuffer();
            int strBufLen = 0;
            // 其他参数
            for (String key : requestParams.keySet()) {
                if (requestParams.get(key) instanceof Collection<?>) {
                    List<Object> list = (List<Object>) requestParams.get(key);
                    for (Object object : list) {
                        strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                        strBuf.append("Content-Disposition: form-data; " + "name=\" " + key + "\"\r\n\r\n");
                        strBuf.append(object.toString());
                        dos.write(strBuf.toString().getBytes());
                        // 清空 StringBuffer
                        strBufLen = strBuf.length();
                        strBuf.delete(0, strBufLen);
                    }
                } else {
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; " + "name=\" " + key + "\"\r\n\r\n");
                    strBuf.append(requestParams.get(key));
                    dos.write(strBuf.toString().getBytes());
                    // 清空 StringBuffer
                    strBufLen = strBuf.length();
                    strBuf.delete(0, strBufLen);
                }
            }
 
            // 文件
            for (File file : files) {
                strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                strBuf.append("Content-Disposition: form-data; " + "name=\"files\";filename=\"" + file.getName()+ "\"\r\n\r\n");
                dos.write(strBuf.toString().getBytes());
                // 清空 StringBuffer
                strBufLen = strBuf.length();
                strBuf.delete(0, strBufLen);
 
                // 文件数据部分
                DataInputStream in = new DataInputStream(new FileInputStream(file));
                int bytes = 0;
                byte[] bufferOut = new byte[in.available()];
                while ((bytes = in.read(bufferOut)) != -1) {
                    dos.write(bufferOut, 0, bytes);
                }
                in.close();
                //dos.write("\r\n".getBytes());
            }
 
            // 结尾
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            dos.write(endData);
 
            dos.flush();
 
            //获得响应状态
            int resultCode = httpConn.getResponseCode();
            if (HttpURLConnection.HTTP_OK == resultCode) {
                StringBuffer sb = new StringBuffer();
                String readLine = new String();
                responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine);
                }
 
//                System.out.println(sb.toString());
                log.info(sb.toString());
//                JSONObject json = JSONObject.parseObject(sb.toString(),JSONObject.class);
                return sb.toString();
            }
 
        } catch (Exception e) {
            System.out.println(e);
            log.error("post 请求失败:" + url);
        } finally {
            if(null != responseReader) responseReader.close();
            if(null != dos) dos.close();
        }
        return null;
    }
}