WechatUtils.java
23.7 KB
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
/**
* Copyright (C), 2015-2018, 广联赛讯有限公司
* FileName: WechatUtils
* Author: liuyf
* Date: 2018/4/27 12:56
* Description: 微信工具类
* History:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package com.glsx.common.utils.wehcat;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsx.common.constants.Constants;
import com.glsx.common.feign.client.CommonClient;
import com.glsx.common.utils.HttpUtils;
import com.glsx.common.utils.PropertiesUtil;
import com.glsx.common.utils.RedisCacheUtil;
/**
* 〈一句话功能简述〉<br>
* 〈微信工具类〉
* 微信公众号相关工具类
* @author liuyf
* @create 2018/4/27
* @since 1.0.0
*/
@Component("wechatUtils")
public class WechatUtils {
private static Logger logger = LoggerFactory.getLogger(WechatUtils.class);
public String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID$&secret=$SECRET$";
public String GET_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$ACCESS_TOKEN$&type=jsapi";
public String GET_MEDIA_URL = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$ACCESS_TOKEN$&media_id=$MEDIA_ID$";
public String GET_OPENID_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$APPID$&secret=$SECRET$&code=$CODE$&grant_type=authorization_code";
public String SEND_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
public String GET_USER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$ACCESS_TOKEN$&openid=$OPENID$&lang=zh_CN";
public String GET_WECHAT_PUBLIC_CODE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$APPID$&redirect_uri=$REDIRECT_URI$&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
public String GET_WXACODE_UNLIMIT = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$ACCESS_TOKEN$";
public String BANK_CARD_OCR_URL = "https://api.weixin.qq.com/cv/ocr/bankcard?type=photo&img_url=$IMG_URL$&access_token=$ACCESS_TOKEN$";
public String ID_CARD_OCR_URL = "https://api.weixin.qq.com/cv/ocr/idcard?type=photo&img_url=$IMG_URL$&access_token=$ACCESS_TOKEN$";
public String BANK_CARD_OCR_URL2 = "https://api.weixin.qq.com/cv/ocr/bankcard?type=scan&access_token=$ACCESS_TOKEN$";
public String ID_CARD_OCR_URL2 = "https://api.weixin.qq.com/cv/ocr/idcard?type=scan&access_token=$ACCESS_TOKEN$";
@Resource
RedisCacheUtil redisCacheUtil;
@Autowired
private CommonClient commonClient;
/**
* 获取微信token和ticket
*
* @return
* @throws Exception
*/
public Map<String, String> getWechatTokenAndTicket(String appid, String secret) throws Exception {
Map<String, String> wtt = new HashMap<String, String>();
String access_token = getWechatToken(appid, secret);
String ticket = getWechatTicket(appid, secret, access_token);
wtt.put("token", access_token);
wtt.put("ticket", ticket);
wtt.put("appid", appid);
return wtt;
}
/**
* 获取微信token
*
* @param appid
* @param secret
* @return
* @throws Exception
*/
private String getWechatToken(String appid, String secret) throws Exception {
String tokenCacheKey = Constants.WECHAT_TOKEN_KEY + appid;
String access_token = (String) redisCacheUtil.getCacheObject(tokenCacheKey);
logger.info("公众号缓存token:" + access_token);
if (StringUtils.isEmpty(access_token)) {
access_token = getAndCacheWechatToken(appid, secret);
}
return access_token;
}
/**
* 获取并缓存微信token
*
* @param appid
* @param secret
* @return
* @throws Exception
*/
private String getAndCacheWechatToken(String appid, String secret) throws Exception {
String access_token = "";
String url = GET_TOKEN_URL.replace("$APPID$", appid).replace("$SECRET$", secret);
HttpUtils httpUtils = new HttpUtils();
String result = httpUtils.get(url, null);
logger.info(url + " 获取token接口返回:" + result);
//{"access_token":"10_hMYT_8NG0GFfM4jkqVSNdWT4QaVIb3SRVhdOfsyj3AkPxXHmeY9uXwC43WgpwJ3xWJt2Ti7RuiOWEVDPVD1sI3ksPaZxc8x2UBsRfElJNM0","expires_in":7200,"refresh_token":"10_In3tQS4WISR5vDdxasxh4j2017NW_VfKr6S2EUITlqk0Iy83rUQEUufbZxoA2NrHZqSX-O8_8O5eEhELSx54X860ttGLh0I0BGtAlVoVeMs","openid":"oxAQwwMiYESDE8--YOopaAl6F4uo","scope":"snsapi_userinfo"}
if (StringUtils.isNotEmpty(result)) {
JSONObject tokenJO = JSON.parseObject(result);
if (tokenJO.containsKey("access_token")) {
access_token = tokenJO.getString("access_token");
//long expires_in = tokenJO.getLongValue("expires_in");
//过期时间设置为10分钟
long expires_in=600;
String tokenCacheKey = Constants.WECHAT_TOKEN_KEY + appid;
redisCacheUtil.setCacheObject(tokenCacheKey, access_token, expires_in, TimeUnit.SECONDS);
}
}
return access_token;
}
/**
* 获取微信ticket
*
* @param appid
* @param secret
* @param access_token
* @return
* @throws Exception
*/
public String getWechatTicket(String appid, String secret, String access_token) throws Exception {
String ticketCacheKey = Constants.WECHAT_TICKET_KEY + appid;
String ticket = (String) redisCacheUtil.getCacheObject(ticketCacheKey);
logger.info("公众号缓存ticket:" + ticket);
if (StringUtils.isEmpty(ticket)) {
String url = GET_TICKET_URL.replace("$ACCESS_TOKEN$", access_token);
String result = HttpUtils.get(url, null);
//{"errcode":0,"errmsg":"ok","ticket":"kgt8ON7yVITDhtdwci0qecVGaUkK4of6P4yBMM24dNWF-d8bPguhmuKFE88bG1x85CnMARKyTniiHR6NtL55bw","expires_in":7200}
//{"errcode":40001,"errmsg":"invalid credential, access_token is invalid or not latest hint: [KWDItA0150a456!]"}
logger.info(url + " 获取ticket返回:" + result);
JSONObject ticketJO = JSON.parseObject(result);
if (ticketJO.containsKey("ticket")) {
ticket = ticketJO.getString("ticket");
long expires_in = ticketJO.getLongValue("expires_in");
redisCacheUtil.setCacheObject(ticketCacheKey, ticket, expires_in, TimeUnit.SECONDS);
} else {
if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(secret)) return ticket;
access_token = getWechatToken(appid, secret);
ticket = getWechatTicket(null, null, access_token);
}
}
return ticket;
}
/**
* 获取微信ticket
*
* @param appid
* @param secret
* @param openId
* @return
* @throws Exception
*/
public Map<String, Object> getWechatUserInfo(String appid, String secret, String openId) throws Exception {
Map<String, Object> wu = new HashMap<String, Object>();
//获取token
String accessToken = getWechatToken(appid, secret);
if (StringUtils.isNotEmpty(accessToken)) {
String url = GET_USER_INFO_URL.replace("$ACCESS_TOKEN$", accessToken).replace("$OPENID$", openId);
HttpUtils httpUtils = new HttpUtils();
String result = httpUtils.get(url, null);
logger.info(url + " 获取UserInfo返回:" + result);
JSONObject ticketJO = JSON.parseObject(result);
// 成功
// {
// "subscribe": 1,
// "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
// "nickname": "Band",
// "sex": 1,
// "language": "zh_CN",
// "city": "Guangzhou",
// "province": "Guangdong",
// "country": "China",
// "headimgurl": "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
// "subscribe_time": 1382694957,
// "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL",
// "remark": "",
// "groupid": 0,
// "tagid_list":[128,2],
// "subscribe_scene": "ADD_SCENE_QR_CODE",
// "qr_scene": 98765,
// "qr_scene_str": ""
// }
// 失败
// {"errcode":40001,"errmsg":"invalid credential, access_token is invalid or not latest hint: [fBBCDa06263401!]"}
if (ticketJO.containsKey("errcode") && 40001 == ticketJO.getIntValue("errcode")) {
accessToken = getAndCacheWechatToken(appid, secret);//重新获取token
url = GET_USER_INFO_URL.replace("$ACCESS_TOKEN$", accessToken).replace("$OPENID$", openId);
result = httpUtils.get(url, null);
logger.info(url + " 重新获取UserInfo返回:" + result);
}
wu.putAll(ticketJO);
}
return wu;
}
/**
* 获取微信token和opendId
*
* @param appid
* @param secret
* @param code
* @return
* @throws Exception
*/
public Map<String, Object> getWechatTokenAndOpenId(String appid, String secret, String code) throws Exception {
Map<String, Object> wto = new HashMap<String, Object>();
String url = GET_OPENID_URL.replace("$APPID$", appid).replace("$SECRET$", secret).replace("$CODE$", code);
HttpUtils httpUtils = new HttpUtils();
String result = httpUtils.get(url, null);
logger.info(url + " 获取openId接口返回:" + result);
// {
// "access_token": "OezXcEiiBSKSxW0eoylIeAsR0GmYd1awCffdHgb4fhS_KKf2CotGj2cBNUKQQvj-G0ZWEE5-uBjBz941EOPqDQy5sS_GCs2z40dnvU99Y5AI1bw2uqN--2jXoBLIM5d6L9RImvm8Vg8cBAiLpWA8Vw",
// "expires_in": 7200,
// "refresh_token": "OezXcEiiBSKSxW0eoylIeAsR0GmYd1awCffdHgb4fhS_KKf2CotGj2cBNUKQQvj-G0ZWEE5-uBjBz941EOPqDQy5sS_GCs2z40dnvU99Y5CZPAwZksiuz_6x_TfkLoXLU7kdKM2232WDXB3Msuzq1A",
// "openid": "oLVPpjqs9BhvzwPj5A-vTYAX3GLc",
// "scope": "snsapi_userinfo,"
// }
if (StringUtils.isNotEmpty(result)) {
JSONObject openIdJO = JSON.parseObject(result);
for (String key : openIdJO.keySet()) {
wto.put(key, openIdJO.getString(key));
}
}
wto.put("appid", appid);
return wto;
}
@SuppressWarnings("static-access")
public void sendTemplateMessage(WechatTemplate wechatTemplate) {
String appid = PropertiesUtil.getProperty(Constants.WECHAT_BHG_PUBLIC_APPID);
String secret = PropertiesUtil.getProperty(Constants.WECHAT_BHG_PUBLIC_SECRET);
try {
String access_token = this.getWechatToken(appid, secret);
String url = this.SEND_MESSAGE_URL + access_token;
String para = JSON.toJSONString(wechatTemplate);
String resultStr = sendWeCharMsg(para, url);
logger.info("返回结果:" + resultStr);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送模板信息调用的请求方法
*
* @param json
* @param url
* @return
*/
public static String sendWeCharMsg(String json, String url) {
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result = "";
try {
StringEntity s = new StringEntity(json, "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(s);
// 发送请求
HttpResponse httpResponse = HttpClients.createDefault().execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
result = strber.toString();
logger.info(result);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
logger.info("请求服务器成功,做相应处理");
} else {
logger.info("请求服务端失败");
}
} catch (Exception e) {
logger.error("请求异常");
throw new RuntimeException(e);
}
return result;
}
@SuppressWarnings({ "rawtypes", "unchecked", })
public Map<String, String> getWxacodeUnlimit(String sceneStr) {
Map<String, String> returnMap = new HashMap<>(4);
returnMap.put("code", "500");
String appid = PropertiesUtil.getProperty(Constants.WECHAT_MINI_MECHANIC_APPID);
String secret = PropertiesUtil.getProperty(Constants.WECHAT_MINI_MECHANIC_SECRET);
// 生成二维码只能跳正式页面,所以测试环境暂时跳转到趣融,正式正式环境需要注释下面两行代码/////TODO
// appid = "wxb947dfc134eadbc4";
// secret = "9cbe8bab22f3b38ec9f0cb373a547516";
// 技工注册的跳转页面
String page = "pages/register/register";
String accessToken = null;
try {
accessToken = this.getWechatToken(appid, secret);
} catch (Exception e) {
logger.error("获取小程序access_token请求异常!");
throw new RuntimeException(e);
}
// 二维码存放路径
RestTemplate rest = new RestTemplate();
String url = this.GET_WXACODE_UNLIMIT.replace("$ACCESS_TOKEN$", accessToken);
Map<String, Object> param = new HashMap<>();
param.put("scene", sceneStr);
param.put("page", page);
param.put("width", 430);
param.put("auto_color", false);
Map<String, Object> line_color = new HashMap<>();
line_color.put("r", 0);
line_color.put("g", 0);
line_color.put("b", 0);
param.put("line_color", line_color);
logger.info("调用生成微信URL接口传参:" + param);
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
HttpEntity requestEntity = new HttpEntity(param, headers);
ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
logger.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
byte[] result = entity.getBody();
String img = Base64.encodeBase64String(result);
if (img.startsWith("/9j/")) {
// 二维码生成成功
logger.info(img);
JSONObject jb = commonClient.uploadQRImage(result);
if (jb != null && jb.containsKey("data")) {
returnMap.put("code", "200");
returnMap.put("img", jb.getString("data"));
return returnMap;
} else {
entity.getStatusCode();
returnMap.put("msg", "保存二维码出错!");
}
}
logger.error("调用小程序生成微信永久小程序码URL接口异常!所传page页面不存在,或者小程序没有发布!");
return returnMap;
}
public Map<String, String> bankCardOcr(String imgUrl) {
HttpUtils httpUtils = new HttpUtils();
Map<String, String> returnMap = new HashMap<>(4);
returnMap.put("code", "500");
String appid = PropertiesUtil.getProperty(Constants.WECHAT_MINI_MECHANIC_APPID);
String secret = PropertiesUtil.getProperty(Constants.WECHAT_MINI_MECHANIC_SECRET);
String accessToken = null;
try {
imgUrl = URLEncoder.encode(imgUrl, "UTF-8");
accessToken = this.getWechatToken(appid, secret);
} catch (Exception e) {
logger.error("获取小程序access_token请求异常!");
throw new RuntimeException(e);
}
String url = this.BANK_CARD_OCR_URL.replace("$ACCESS_TOKEN$", accessToken).replace("$IMG_URL$", imgUrl);
String result;
try {
result = httpUtils.post(url, null);
} catch (Exception e) {
logger.error("银行卡ocr请求异常!");
throw new RuntimeException(e);
}
if (!StringUtils.isEmpty(result)) {
JSONObject jb = JSON.parseObject(result);
if (0 == jb.getInteger("errcode")) {
returnMap.put("code", "200");
returnMap.put("number", jb.getString("number"));
return returnMap;
}
}
return returnMap;
}
public Map<String, String> IDCardOcr(String imgUrl) {
HttpUtils httpUtils = new HttpUtils();
Map<String, String> returnMap = new HashMap<>(4);
returnMap.put("code", "500");
String appid = PropertiesUtil.getProperty(Constants.WECHAT_MINI_MECHANIC_APPID);
String secret = PropertiesUtil.getProperty(Constants.WECHAT_MINI_MECHANIC_SECRET);
String accessToken = null;
try {
accessToken = this.getWechatToken(appid, secret);
imgUrl = URLEncoder.encode(imgUrl, "UTF-8");
} catch (Exception e) {
logger.error("获取小程序access_token请求异常!");
throw new RuntimeException(e);
}
String url = this.ID_CARD_OCR_URL.replace("$ACCESS_TOKEN$", accessToken).replace("$IMG_URL$", imgUrl);
String result = null;
try {
result = httpUtils.post(url, null);
} catch (Exception e) {
logger.error("身份证ocr请求异常!");
throw new RuntimeException(e);
}
if (!StringUtils.isEmpty(result)) {
JSONObject jb = JSON.parseObject(result);
returnMap.put("code", jb.getInteger("errcode").toString());
if (0 == jb.getInteger("errcode")) {
returnMap.put("code", "200");
String type = jb.getString("type");
returnMap.put("type", type);
if ("front".equalsIgnoreCase(type)) {
returnMap.put("data", jb.getString("id"));
} else {
returnMap.put("data", jb.getString("valid_date"));
}
return returnMap;
}
}
return returnMap;
}
/**
* 上传图片
*
* @param urlStr
* @param textMap
* @param fileMap
* @param contentType
* 没有传入文件类型默认采用application/octet-stream
* contentType非空采用filename匹配默认的图片类型
* @return 返回response数据
*/
public JSONObject postMultipart(MultipartFile img, String type) {
JSONObject jb = new JSONObject();
String res = "";
String urlStr = BANK_CARD_OCR_URL2;
if ("idcard".equals(type)) {
urlStr = ID_CARD_OCR_URL2;
}
String accessToken = null;
String appid = PropertiesUtil.getProperty(Constants.WECHAT_MINI_MECHANIC_APPID);
String secret = PropertiesUtil.getProperty(Constants.WECHAT_MINI_MECHANIC_SECRET);
try {
accessToken = this.getWechatToken(appid, secret);
} catch (Exception e) {
logger.error("获取小程序access_token请求异常!");
throw new RuntimeException(e);
}
urlStr = urlStr.replace("$ACCESS_TOKEN$", accessToken);
HttpURLConnection conn = null;
// boundary就是request头和上传文件内容的分隔符
String BOUNDARY = "---------------------------" + System.currentTimeMillis() + Math.random() * 1000;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
// conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U;
// Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// file
// 获取文件后缀
// 获取文件名
String filename = img.getOriginalFilename();
String prefix = filename.substring(filename.lastIndexOf("."));
final File file = File.createTempFile(UUID.randomUUID().toString(), prefix);
img.transferTo(file);
// 没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
String contentType = new MimetypesFileTypeMap().getContentType(file);
// contentType非空采用filename匹配默认的图片类型
if (!"".equals(contentType)) {
if (filename.endsWith(".png")) {
contentType = "image/png";
} else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
contentType = "image/jpeg";
} else if (filename.endsWith(".gif")) {
contentType = "image/gif";
} else if (filename.endsWith(".ico")) {
contentType = "image/image/x-icon";
}
}
if (contentType == null || "".equals(contentType)) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append(
"Content-Disposition: form-data;" + "\"; filename=\"" + filename + img.getName() + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf1 = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf1.append(line).append("\n");
}
res = strBuf1.toString();
jb = JSONObject.parseObject(res);
file.delete();
reader.close();
reader = null;
} catch (Exception e) {
System.out.println("发送OCR请求出错。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return jb;
}
}