jack
2024-03-16 3bb8f2ad72748a2477758e591cd18833d9f82a61
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package com.nq.utils.pay;
 
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.map.LinkedMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
 
public class CmcPayOuterRequestUtil {
 
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
 
            URL realUrl = new URL(url);
            // 打開和URL之間的連接
            URLConnection connection = realUrl.openConnection();
            // 設置通用的請求屬性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立實際的連接
            connection.connect();
 
            // 定義 BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally塊來關閉輸入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
 
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打開和URL之間的連接
            URLConnection connection = realUrl.openConnection();
            // 設置通用的請求屬性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立實際的連接
            connection.connect();
 
            // 定義 BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally塊來關閉輸入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
 
    public static String sendGet(String url, LinkedMap params) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = getUrlString(url, params);
            URL realUrl = new URL(urlNameString);
            // 打開和URL之間的連接
            URLConnection connection = realUrl.openConnection();
            // 設置通用的請求屬性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立實際的連接
            connection.connect();
 
            // 定義 BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally塊來關閉輸入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
 
    public static String getUrlString(String url, LinkedMap params) throws UnsupportedEncodingException {
        return url + "?" + getParamsString(params);
    }
 
    /**
     * 封裝HTTP POST方法
     * @param
     * @param (如JSON串)
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String post(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> formparams = setHttpParams(paramMap);
        UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "utf-8");
        httpPost.setEntity(param);
        HttpResponse response = httpClient.execute(httpPost);
        String httpEntityContent = getHttpEntityContent(response);
        httpPost.abort();
        return httpEntityContent;
    }
 
    /**
     * 設置請求參數
     * @param
     * @return
     */
    private static List<NameValuePair> setHttpParams(Map<String, String> paramMap) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> set = paramMap.entrySet();
        for (Map.Entry<String, String> entry : set) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return formparams;
    }
 
    /**
     * 獲得響應HTTP實體內容
     * @param response
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    private static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream is = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = br.readLine();
            StringBuilder sb = new StringBuilder();
            while (line != null) {
                sb.append(line + "\n");
                line = br.readLine();
            }
            return sb.toString();
        }
        return "";
    }
 
    /**
     * 向指定 URL 發送POST方法的請求
     *
     * @param url    發送請求的 URL
     * @param params 請求參數,請求參數应该是 name1=value1&name2=value2 的形式。
     * @return 所代表遠程資源的響應結果
     */
    public static String sendPost(String url, LinkedMap params) throws IOException {
        // Post請求的url,與get不同的是不需要帶參數
//        URL postUrl = new URL("http://127.0.0.1:8088/mall/user/test");
        String result = "";
        URL postUrl = new URL(url);
        // 打開連接
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
 
        // 設置是否向connection輸出,因為這個是post請求,參數要放在
        // http正文內,因此需要設為true
        connection.setDoOutput(true);
        // Read from the connection. Default is true.
        connection.setDoInput(true);
        // 默認是 GET方式
        connection.setRequestMethod("POST");
 
        // Post 請求不能使用緩存
        connection.setUseCaches(false);
 
        connection.setInstanceFollowRedirects(true);
 
        // 配置本次連接的Content-type,配置為application/x-www-form-urlencoded的
        // 意思是正文是urlencoded編碼過的form參數,下面我們可以看到我們對正文內容使用URLEncoder.encode
        // 進行編碼
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // 連接,從postUrl.openConnection()至此的配置必須要在connect之前完成,
        // 要注意的是connection.getOutputStream會隱含的進行connect。
 
 
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        // The URL-encoded contend
        // 正文,正文內容其實跟get的URL中 '? '后的參数字符串一致
//        String content = "account=" + URLEncoder.encode("一個大肥人", "UTF-8");
//        content +="&pswd="+URLEncoder.encode("兩個個大肥人", "UTF-8");
//        // DataOutputStream.writeBytes將字符串中的16位的unicode字符以8位的字符形式寫到流裏面
//        out.writeBytes(content);
        String content = getParamsString(params);
        out.writeBytes(content);
        out.flush();
        out.close();
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            result += line;
        }
 
        reader.close();
        connection.disconnect();
        return result;
    }
 
    public static String getParamsString(LinkedMap params) throws UnsupportedEncodingException {
        String content = new String();
        Set<String> keySet = params.keySet();
        String[] keys = keySet.toArray(new String[keySet.size()]);
        for (String key : keys) {
            String value = (String)params.get(key);
            if (value == null) continue;
            if (content.length() != 0) content += "&";
            content += key + "=" + URLEncoder.encode(value, "UTF-8");
        }
        return content;
    }
 
    private static final String SIGN_KEY = "sign";
 
    /** 密鑰屬性名key**/
    private static final String SECRET_KEY = "key";
    /**
     * 計算簽名
     *
     * @param jsonObj
     *            要參与簽名的json數據
     * @param md5Key
     *            密鑰
     * @return 簽名
     */
    public static String getSign(LinkedMap jsonObj, String md5Key) {
        if (jsonObj == null || jsonObj.isEmpty()) {
            return null;
        }
        String str2Sign = buildParam4Sign(jsonObj, SIGN_KEY, md5Key);
        try {
            byte[] data = str2Sign.getBytes("utf-8");
            String result = DigestUtils.md5Hex(data);
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 拼接用於簽名的參數
     * @param jsonObj
     * @return
     */
    private static String buildParam4Sign(LinkedMap jsonObj, String signKey, String md5Key) {
        Set<String> keySet = jsonObj.keySet();
        StringBuilder param = new StringBuilder(20 * keySet.size());
        String[] keys = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keys, String.CASE_INSENSITIVE_ORDER);
        /*for (String key : keys) {
            // 排除sign
            if (signKey.equals(key)) {
                continue;
            }
            Object value = jsonObj.get(key);
            // 排除值為null的情況
            param.append(key).append("=").append(value).append("&");
            //param.append(key).append("=").append(value);
        }
        param.deleteCharAt(param.length()-1);
        param.append(md5Key);*/
        param.append(jsonObj.get("merchantid"));
        param.append(jsonObj.get("orderno"));
        param.append(jsonObj.get("orderamount"));
        param.append(jsonObj.get("serverbackurl"));
        param.append(jsonObj.get("callbackurl"));
        param.append(md5Key);
        System.out.println(param.toString());
        return param.toString();
    }
 
    public static String getSignH5(LinkedMap jsonObj, String md5Key)  throws Exception{
        if (jsonObj == null || jsonObj.isEmpty()) {
            return null;
        }
        StringBuilder param = new StringBuilder();
        param.append("appid="+jsonObj.get("appid"));
        param.append("&data="+jsonObj.get("data"));
        param.append("&money="+jsonObj.get("money"));
        param.append("&type="+jsonObj.get("type"));
        param.append("&uip="+jsonObj.get("uip"));
        param.append("&appkey="+md5Key);
        String str2Sign = param.toString().toLowerCase();
        try {
            /*byte[] data = str2Sign.getBytes("utf-8");
            String result = DigestUtils.md5Hex(data);*/
            String result = encryption(str2Sign);
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * md5加密 32位 小寫
     * @param plainText
     * @return
     */
    public static String encryption(String plainText)  throws Exception{
        String re_md5 = new String();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
 
            int i;
 
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
 
            re_md5 = buf.toString();
 
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return re_md5;
    }
 
 
}