许鹏程
2025-02-10 ef26bf4fde77ba361bcd083a769c3a1b8a229738
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package com.product.file.util;
 
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
public class HttpTest {
    protected static Logger logger = LoggerFactory.getLogger(HttpTest.class);
 
    static String uri = "http://127.0.0.1:9998/lx";
    private static final String ACCESS_TOKEN = "token";
    private static final String language="zh-CN";//zh-CN en
    private static final String systemClientVersion="1.0.0";
    private static final String systemClientType="Web";
 
    /**
     * 支持文件上传的接口调用
     */
    public static void testFileUpload(Map<String, Object> map) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            Object token = map.get("token");
            Object cookies = map.get("cookie");
            String cookie[] = new String[2];
            if (token == null) {
                cookie = com.product.common.utils.HttpTest.login();
            } else {
                cookie[0] = cookies.toString();
                cookie[1] = token.toString();
            }
            logger.info("cookie[0]="+cookie[0]+"------cookie[1]="+cookie[1]+"------------------------------------");
            if (cookie == null || cookie[1] == null) {
                return;
            }
            String url = null;
            Map<String, String> fileMap = null;
            JSONObject jsonParam = new JSONObject();
            for (String key : map.keySet()) {// keySet获取map集合key的集合  然后在遍历key即可
                if ("url/api".equals(key.trim())) {
                    url = map.get(key).toString();
                } else if ("data".equals(key)) {
                    Map value = (Map) map.get(key);//
                    jsonParam.put(key, value);
                } else if ("fileMap".equals(key)) {
                    fileMap = (Map) map.get(key);
                } else if (map.get(key) instanceof List) {
                    List value = (List) map.get(key);//
                    jsonParam.put(key, value);
                } else {
                    jsonParam.put(key, map.get(key));
                }
            }
            jsonParam.put(ACCESS_TOKEN, cookie[1]);
 
            List<BasicNameValuePair> parames = new ArrayList<>();
            logger.info("上传json:" + jsonParam.toString());
            parames.add(new BasicNameValuePair("formData", jsonParam.toString()));
 
            HttpPost httppost = new HttpPost(uri + url);
            httppost.addHeader("Cookie", cookie[0]);
            httppost.addHeader("system-language-code", HttpTest.language);
            httppost.addHeader("system-client-type", HttpTest.systemClientType);
            httppost.addHeader("system-client-version", HttpTest.systemClientVersion);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000)
                    .build();
            httppost.setConfig(requestConfig);
 
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            for (Map.Entry<String, String> entry : fileMap.entrySet()) {
                multipartEntityBuilder.addPart(entry.getKey(), new FileBody(new File(entry.getValue())));
            }
            StringBody comment = new StringBody(jsonParam.toString(), ContentType.TEXT_PLAIN);
            multipartEntityBuilder.addPart("formData", comment);
            HttpEntity reqEntity = multipartEntityBuilder.build();
 
            System.out.println("上传参数:" + jsonParam);
            httppost.setEntity(reqEntity);
            System.out.println("executing request " + httppost.getRequestLine());
            response = httpclient.execute(httppost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String responseEntityStr = EntityUtils.toString(response.getEntity());
                    System.out.println(responseEntityStr);
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 支持文件下载的接口调用
     */
    public static void testFileDownload(Map<String, Object> map) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            CloseableHttpResponse response = null;
            Object token = map.get("token");
            Object cookies = map.get("cookie");
            String cookie[] = new String[2];
            if (token == null) {
                cookie = com.product.common.utils.HttpTest.login();
            } else {
                cookie[0] = cookies.toString();
                cookie[1] = token.toString();
            }
            logger.info("cookie[0]="+cookie[0]+"------cookie[1]="+cookie[1]+"------------------------------------");
            if (cookie == null || cookie[1] == null) {
                return;
            }
            String url = null;
            JSONObject jsonParam = new JSONObject();
            for (String key : map.keySet()) {// keySet获取map集合key的集合  然后在遍历key即可
                if ("url/api".equals(key.trim())) {
                    url = map.get(key).toString();
                } else if ("data".equals(key)) {
                    Map value = (Map) map.get(key);//
                    jsonParam.put(key, value);
                } else if (map.get(key) instanceof List) {
                    List value = (List) map.get(key);//
                    jsonParam.put(key, value);
                } else {
                    jsonParam.put(key, map.get(key));
                }
            }
            jsonParam.put(ACCESS_TOKEN, cookie[1]);
 
            List<BasicNameValuePair> parames = new ArrayList<>();
            logger.info("上传json:" + jsonParam.toString());
            parames.add(new BasicNameValuePair("formData", jsonParam.toString()));
 
            HttpPost httppost = new HttpPost(uri + url);
            httppost.addHeader("Cookie", cookie[0]);
            httppost.addHeader("system-language-code", HttpTest.language);
            httppost.addHeader("system-client-type", HttpTest.systemClientType);
            httppost.addHeader("system-client-version", HttpTest.systemClientVersion);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
            httppost.setConfig(requestConfig);
 
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            StringBody comment = new StringBody(jsonParam.toString(), ContentType.TEXT_PLAIN);
            multipartEntityBuilder.addPart("formData", comment);
            HttpEntity reqEntity = multipartEntityBuilder.build();
 
            httppost.setEntity(reqEntity);
            System.out.println("executing request " + httppost.getRequestLine());
            response = httpclient.execute(httppost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println(reqEntity.getContentLength());
                    System.out.println(reqEntity.getContentType());
//                    String responseEntityStr = EntityUtils.toString(response.getEntity());
//                    System.out.println(responseEntityStr);
//                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}