67,513
社区成员
发帖
与我相关
我的任务
分享
package com.haozhong.recharge.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
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 org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.haozhong.recharge.bean.recharge.LianLianInterface;
/**
*
*/
public class Lianlian {
private MyHttp http = new MyHttp();
public String getCheckCode(String path){
//始初化验证码变量
String code = null;
for(int i = 0; i < 10; i++)
{
//图片的网址
String imgUrl = "http://www.lianlian.com/servlet/CheckCodeServlet";
//图片的本地路径
String imgSaveUrl = path+"/temp.jpg";
http.saveImg(imgUrl, imgSaveUrl);
code = unCode(imgSaveUrl);
if(code != null && code.equals("null") && code.length() == 4)
{
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("得到破解的验证码为="+code);
return code ;
}
public String login(String path ,LianLianInterface lianLianInterface) throws InterruptedException{
try {
String url = "http://www.lianlian.com/login";
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("userName",lianLianInterface.getLoginName()));
nvps.add(new BasicNameValuePair("checkCode", getCheckCode(path)));
nvps.add(new BasicNameValuePair("password", lianLianInterface.getPassword()));
String outdata = http.post(url, nvps);
if ( outdata.indexOf("短信验证码必须是") >= 0)
{
System.out.println("检测到返回的html代码中含有<短信码>字样,登陆成功");
}
else
{
System.out.println("检测到返回的html代码中没有含有<短信码>字样,登陆失败," +
"下面是返回的html代码,请查看失败原因");
System.out.println("返回的网址html字符="+outdata);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null ;
}
public String getCookie(String path,LianLianInterface lianLianInterface ){
try {
String outdata = login(path,lianLianInterface);
Pattern p = Pattern.compile("http(.)+?LLISP_ZJ/ISPSimulateLogin.do\\?params=(.)+?\"");
String url = "" ;
Matcher m = p.matcher(outdata);
if(m.find())
{
url = m.group();
url = url.substring(0, url.length()-1);
}
System.out.println("正则后的URL="+url);
http.get(url);
String cookies = http.getCookie( "llagtzj.lianlian.com.cn");
System.out.println("***************************");
System.out.println(cookies);
return cookies ;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null ;
}
public static void main(String[] args) throws Exception {
LianLianInterface lianLianInterface = new LianLianInterface();
lianLianInterface.setLoginName("15988641192");
lianLianInterface.setPassword("100860");
//ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext*.xml");
String path = "c:";
new Lianlian().getCookie(path,lianLianInterface);
}
/**
* 根据传入的图片本地路径破解验证码
* @param imgSaveUrl
* @return
*/
public String unCode(String imgSaveUrl)
{
String code = "";
try {
code = OCRUtil.recognizeValidation(imgSaveUrl);
//doSoming
//请完善破解验证码的代码
} catch (Exception e) {
// TODO: handle exception
}
return code;
}
public MyHttp getHttp() {
return http;
}
public void setHttp(MyHttp http) {
this.http = http;
}
}
public String saveCookies() throws InterruptedException{
String path = "c:";
LianLianInterface lianLianInterface = new LianLianInterface();
lianLianInterface = lianLianInterfaceService.findByStatus();
String cookie = new Lianlian().getCookie(path,lianLianInterface);
lianLianInterface.setJsessionid(cookie.split("=")[1]);
rechargeService.updateLianLianInterface(lianLianInterface);
request.setAttribute("cookie", cookie);
return "saveCookies" ;
}
Iterator<ImageWriter> writers = ImageIO
.getImageWritersByFormatName("tiff");
ImageWriter writer = writers.next();
package com.haozhong.recharge.util;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.sun.media.imageio.plugins.tiff.TIFFImageWriteParam;
public class OCRUtil {
private static final Log logger = LogFactory.getLog(OCRUtil.class);
private static final String LANG_OPTION = "-l";
private static final String EOL = File.separator;
private static final String IMAGE_FORMAT = "jpg";
// public static String recognizeValidation(InputStream in) throws Exception {
public static String recognizeValidation(String imgUrl) throws Exception {
//File tmpFile = File.createTempFile("img", "." + IMAGE_FORMAT);
//File tmpFile = new File("c:/temp."+IMAGE_FORMAT);
// OutputStream out = new FileOutputStream(tmpFile);
File tmpFile = new File(imgUrl);
//IOUtils.copy(in, out);
// IOUtils.closeQuietly(out);
return format(recognizeText(tmpFile, IMAGE_FORMAT));
}
private static String format(String str) {
if (StringUtils.isBlank(str)) {
return null;
}
StringBuffer sb = new StringBuffer(str.length());
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isDigit(c) || Character.isLetter(c)) {
sb.append(c);
}
}
return sb.toString();
}
public static String recognizeText(File imageFile, String imageFormat)
throws Exception {
File tempImage = createImage(imageFile, imageFormat);
File outputFile = new File(imageFile.getParentFile(), "output");
StringBuffer strB = new StringBuffer();
List<String> cmd = new ArrayList<String>();
cmd.add("D:/Program Files/Tesseract-OCR/tesseract.exe");
cmd.add("");
cmd.add(outputFile.getName());
cmd.add(LANG_OPTION);
cmd.add("eng");
ProcessBuilder pb = new ProcessBuilder();
pb.directory(imageFile.getParentFile());
cmd.set(1, tempImage.getName());
pb.command(cmd);
pb.redirectErrorStream(true);
Process process = pb.start();
int w = process.waitFor();
// delete temp working files
tempImage.delete();
if (w == 0) {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(outputFile.getAbsolutePath() + ".txt"),
"UTF-8"));
String str;
while ((str = in.readLine()) != null) {
strB.append(str).append(EOL);
}
in.close();
} else {
String msg;
switch (w) {
case 1:
msg = "Errors accessing files. There may be spaces in your image's filename.";
break;
case 29:
msg = "Cannot recognize the image or its selected region.";
break;
case 31:
msg = "Unsupported image format.";
break;
default:
msg = "Errors occurred.";
}
tempImage.delete();
throw new RuntimeException(msg);
}
new File(outputFile.getAbsolutePath() + ".txt").delete();
// logger.info("图像识别结果:" + strB);
return strB.toString();
}
public static File createImage(File imageFile, String imageFormat) {
File tempFile = null;
try {
Iterator<ImageReader> readers = ImageIO
.getImageReadersByFormatName(imageFormat);
ImageReader reader = readers.next();
ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
reader.setInput(iis);
// Read the stream metadata
IIOMetadata streamMetadata = reader.getStreamMetadata();
// Set up the writeParam
TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(
Locale.US);
tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);
// Get tif writer and set output to file
Iterator<ImageWriter> writers = ImageIO
.getImageWritersByFormatName("tiff");
ImageWriter writer = writers.next();
BufferedImage bi = reader.read(0);
// bi = new ImageFilter(bi).changeGrey();
IIOImage image = new IIOImage(bi, null, reader.getImageMetadata(0));
tempFile = tempImageFile(imageFile);
ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);
writer.setOutput(ios);
writer.write(streamMetadata, image, tiffWriteParam);
ios.close();
writer.dispose();
reader.dispose();
} catch (Exception exc) {
exc.printStackTrace();
logger.error("异常:", exc);
}
return tempFile;
}
private static File tempImageFile(File imageFile) {
String path = imageFile.getPath();
StringBuffer strB = new StringBuffer(path);
strB.insert(path.lastIndexOf('.'), 0);
return new File(strB.toString().replaceFirst("(?<=\\.)(\\w+)$", "tif"));
}
}