Skip to content

Commit 024c77e

Browse files
author
崔成龙
committed
本次升级内容有:
1. 添加多文件上传功能及测试类(HttpAsyncClientUtil暂不支持); 2. 添加请求重试机制(如果请求是幂等的,就再次尝试)。 3. 优化本地验证码图片上传识别优化本地验证码图片上传识别(旧方式改名为OldOCR); 4. 优化http连接池使用策略,添加http连接池性能测试类
1 parent 1b21a6c commit 024c77e

File tree

3 files changed

+598
-0
lines changed

3 files changed

+598
-0
lines changed
Lines changed: 293 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,293 @@
1+
package com.tgb.ccl.http.common.util;
2+
3+
import java.io.BufferedInputStream;
4+
import java.io.ByteArrayOutputStream;
5+
import java.io.File;
6+
import java.io.FileInputStream;
7+
import java.io.FileOutputStream;
8+
import java.io.IOException;
9+
import java.util.HashMap;
10+
import java.util.Map;
11+
import java.util.Map.Entry;
12+
13+
import org.apache.http.Header;
14+
import org.apache.http.client.HttpClient;
15+
16+
import com.tgb.ccl.http.common.HttpConfig;
17+
import com.tgb.ccl.http.common.HttpHeader;
18+
import com.tgb.ccl.http.common.Utils;
19+
import com.tgb.ccl.http.exception.HttpProcessException;
20+
import com.tgb.ccl.http.httpclient.HttpClientUtil;
21+
import com.tgb.ccl.http.httpclient.builder.HCB;
22+
23+
/**
24+
* 识别验证码,自拼接http报文信息
25+
*
26+
* @author arron
27+
* @date 2016年3月24日 上午9:44:35
28+
* @version 1.0
29+
*/
30+
public class OldOCR {
31+
32+
/**
33+
* 接口说明:
34+
* https://github.com/AvensLab/OcrKing/blob/master/线上识别http接口说明.txt
35+
*/
36+
private static final String apiUrl = "http://lab.ocrking.com/ok.html";
37+
private static final String apiKey = PropertiesUtil.getProperty("OCR.key");
38+
private static final String boundary = "----------------------------OcrKing_Client_Aven_s_Lab";
39+
private static final String end="\r\n--" + boundary + "--\r\n";
40+
private static final Header[] headers = HttpHeader.custom()
41+
.accept("text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2")
42+
.userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN; rv:1.9.1.3) Gecko/20100101 Firefox/8.0")
43+
.contentType("multipart/form-data; boundary="+boundary)
44+
.referer("http://lab.ocrking.com/?javaclient0.1)")
45+
.build();
46+
private static final Map<String, Object> map = getParaMap();
47+
private static HttpClient client =null; //=HCB.custom().proxy("127.0.0.1", 8888).build();
48+
49+
public static void enableCatch(){
50+
client =HCB.custom().proxy("127.0.0.1", 8888).build();
51+
}
52+
public static void unEnableCatch(){
53+
client =null;
54+
}
55+
56+
//获取固定参数
57+
private static Map<String, Object> getParaMap(){
58+
//加载所有参数
59+
Map<String , Object> map = new HashMap<String, Object>();
60+
map.put("service", "OcrKingForCaptcha");
61+
map.put("language", "eng");
62+
map.put("charset", "7");//7-数字大写小写,5-数字大写字母
63+
map.put("type", "http://www.unknown.com");
64+
map.put("apiKey", apiKey);
65+
return map;
66+
}
67+
68+
69+
/**
70+
* 识别本地校验码(英文:字母+大小写)
71+
*
72+
* @param imgFilePath 验证码地址
73+
* @return
74+
*/
75+
public static String ocrCode(String filePath){
76+
return ocrCode(filePath, 0);
77+
}
78+
/**
79+
* 识别本地校验码(英文:字母+大小写)
80+
*
81+
* @param imgFilePath 验证码地址
82+
* @param limitCodeLen 验证码长度(如果结果与设定长度不一致,则返回获取失败的提示)
83+
* @return
84+
*/
85+
@SuppressWarnings("resource")
86+
public static String ocrCode(String imgFilePath, int limitCodeLen){
87+
byte[] data = null;
88+
String fileName = imgFilePath.replaceAll("[^/]*/|[^\\\\]*\\\\", "");
89+
90+
StringBuffer strBuf = new StringBuffer();
91+
for (Entry<String, Object> entry : map.entrySet()) {
92+
strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
93+
strBuf.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
94+
strBuf.append(entry.getValue());
95+
}
96+
strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
97+
strBuf.append("Content-Disposition: form-data; name=\"ocrfile\"; filename=\"" + fileName + "\"\r\n");
98+
strBuf.append("Content-Type:application/octet-stream\r\n\r\n");
99+
100+
//读取文件
101+
File f = new File(imgFilePath);
102+
if(!f.exists()){
103+
return "Error:文件不存在!";
104+
}
105+
106+
//内容长度=参数长度+文件长度+结尾字符串长度
107+
ByteArrayOutputStream bos = new ByteArrayOutputStream(strBuf.length()+(int)f.length()+end.length());
108+
try {
109+
bos.write(strBuf.toString().getBytes());//转化参数内容
110+
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
111+
int buf_size = 1024;
112+
int len = 0;
113+
byte[] buf = new byte[buf_size];
114+
while (-1 != (len = in.read(buf, 0, buf_size))) {
115+
bos.write(buf, 0, len);
116+
}
117+
bos.write(end.getBytes());
118+
data= bos.toByteArray();
119+
} catch (IOException e) {
120+
Utils.exception(e);
121+
}
122+
123+
Map<String , Object> m = new HashMap<String, Object>();
124+
m.put(Utils.ENTITY_BYTES, data);
125+
126+
String html;
127+
try {
128+
html = HttpClientUtil.post(HttpConfig.custom().client(client).url(apiUrl).headers(headers).map(m));
129+
//System.out.println(html);
130+
String[] results = StringUtil.regex("<Result>([^<]*)</Result>\\s*<Status>([^<]*)</Status>", html);
131+
if(results.length>0){
132+
//System.out.println(results[0]);
133+
if(Boolean.parseBoolean(results[1])){
134+
if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回
135+
return results[0];
136+
}else{
137+
return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")";
138+
}
139+
}else{
140+
return "Error:获取失败! 原因:"+results[0];
141+
}
142+
}
143+
} catch (HttpProcessException e) {
144+
Utils.exception(e);
145+
}
146+
147+
return "Error:获取失败!";
148+
}
149+
150+
151+
152+
/**
153+
* 直接获取网络验证码(验证码不刷新)
154+
*
155+
* @param imgUrl 验证码地址
156+
* @return
157+
*/
158+
public static String ocrCode4Net(String imgUrl){
159+
return ocrCode4Net(imgUrl, 0);
160+
}
161+
/**
162+
* 直接获取网络验证码(验证码不刷新)
163+
*
164+
* @param imgUrl 验证码地址
165+
* @param limitCodeLen 验证码长度
166+
* @return
167+
*/
168+
public static String ocrCode4Net(String imgUrl, int limitCodeLen){
169+
Map<String, Object> map = getParaMap();
170+
map.put("url", imgUrl);
171+
172+
Header[] headers = HttpHeader.custom().userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN; rv:1.9.1.3) Gecko/20100101 Firefox/8.0").build();
173+
174+
try {
175+
String html = HttpClientUtil.post(HttpConfig.custom().client(client).url(apiUrl).headers(headers).map(map));
176+
//System.out.println(html);
177+
String[] results = StringUtil.regex("<Result>([^<]*)</Result>\\s*<Status>([^<]*)</Status>", html);
178+
if(results.length>0){
179+
//System.out.println(results[0]);
180+
if(Boolean.parseBoolean(results[1])){
181+
if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回
182+
return results[0];
183+
}else{
184+
return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")";
185+
}
186+
}else{
187+
return "Error:获取失败! 原因:"+results[0];
188+
}
189+
}
190+
} catch (HttpProcessException e) {
191+
Utils.exception(e);
192+
}
193+
194+
return "Error:获取失败!";
195+
}
196+
197+
198+
/**
199+
* 直接获取网络验证码(通过获取图片流,然后识别验证码)
200+
*
201+
* @param config HttpConfig对象(设置cookie)
202+
* @param savePath 图片保存的完整路径(值为null时,不保存),如:c:/1.png
203+
* @return
204+
*/
205+
public static String ocrCode4Net(HttpConfig config, String savePath){
206+
return ocrCode4Net(config, savePath, 0);
207+
}
208+
/**
209+
* 直接获取网络验证码(通过获取图片流,然后识别验证码)
210+
*
211+
* @param config HttpConfig对象(设置cookie)
212+
* @param savePath 图片保存的完整路径(值为null时,不保存),如:c:/1.png
213+
* @param limitCodeLen 验证码长度
214+
* @return
215+
*/
216+
@SuppressWarnings("resource")
217+
public static String ocrCode4Net(HttpConfig config, String savePath, int limitCodeLen){
218+
if(savePath==null || savePath.equals("")){//如果不保存图片,则直接使用图片地址的方式获取验证码
219+
return ocrCode4Net(config.url(), limitCodeLen);
220+
}
221+
222+
byte[] data = null;
223+
224+
StringBuffer strBuf = new StringBuffer();
225+
for (Entry<String, Object> entry : map.entrySet()) {
226+
strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
227+
strBuf.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
228+
strBuf.append(entry.getValue());
229+
}
230+
strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
231+
strBuf.append("Content-Disposition: form-data; name=\"ocrfile\"; filename=\"" + "aaa" + "\"\r\n");
232+
strBuf.append("Content-Type:application/octet-stream\r\n\r\n");
233+
234+
//下载图片
235+
ByteArrayOutputStream out = new ByteArrayOutputStream();
236+
try {
237+
out = (ByteArrayOutputStream) HttpClientUtil.down(config.client(client).out(out));
238+
//本地测试,可以保存一下图片,方便核验
239+
FileOutputStream fos = new FileOutputStream(savePath);
240+
fos.write(out.toByteArray());
241+
242+
ByteArrayOutputStream bos = new ByteArrayOutputStream(out.size()+strBuf.length()+end.length());
243+
bos.write(strBuf.toString().getBytes());
244+
bos.write(out.toByteArray());
245+
bos.write(end.getBytes());
246+
data= bos.toByteArray();
247+
} catch (HttpProcessException e) {
248+
Utils.exception(e);
249+
} catch (IOException e) {
250+
Utils.exception(e);
251+
}
252+
253+
Map<String , Object> m = new HashMap<String, Object>();
254+
m.put(Utils.ENTITY_BYTES, data);
255+
256+
String html;
257+
try {
258+
html = HttpClientUtil.post(config.client(client).url(apiUrl).headers(headers).map(m));
259+
//System.out.println(html);
260+
String[] results = StringUtil.regex("<Result>([^<]*)</Result>\\s*<Status>([^<]*)</Status>", html);
261+
if(results.length>0){
262+
//System.out.println(results[0]);
263+
if(Boolean.parseBoolean(results[1])){
264+
if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回
265+
return results[0];
266+
}else{
267+
return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")";
268+
}
269+
}else{
270+
return "Error:获取失败! 原因:"+results[0];
271+
}
272+
}
273+
} catch (HttpProcessException e) {
274+
Utils.exception(e);
275+
}
276+
277+
return "Error:获取失败!";
278+
}
279+
280+
public static void main(String[] args) throws HttpProcessException, IOException {
281+
// enableCatch();
282+
String filePath="C:/Users/160049/Desktop/中国.png";
283+
String url = "http://file.ocrking.net:6080/small/20161104/w4fCjnzCl8KTwphpwqnCv2bCn8Kp/66fcff8d-61b1-49d6-bbfe-7428cf7accdf_debug.png?e9gFvJmkLbmgsZNTUCCNkjfi8J0Wbpn1CZHeP98eT1kxZ0ISBDt8Ql6h6zQ79pJg";
284+
String url2 = "http://59.41.9.91/GZCX/WebUI/Content/Handler/ValidateCode.ashx?0.3271647585525703";
285+
String code1 = ocrCode(filePath, 5);
286+
String code2 = ocrCode4Net(url,5);
287+
String code3 = ocrCode4Net(HttpConfig.custom().url(url2), System.getProperty("user.dir")+System.getProperty("file.separator")+"123.png", 5);
288+
System.out.println(code1);
289+
System.out.println(code2);
290+
System.out.println(code3);
291+
System.out.println("----");
292+
}
293+
}

0 commit comments

Comments
 (0)