问题描述
我想模拟登录一个界面,登陆界面有验证码,我就通过get获取验证码保存到本地,通过ocr识别了验证码,再通过post填写表单数据,发送出去,响应回来的是200,不是302;通过html源码,返回回来的是验证码错误,难道get请求和post请求的不是一张验证码,难道是cookie不一致,httpclient应该具有自动处理cookie的功能啊,搞了一天没成功,郁闷的要死,求大神给点解决的方法,如何保证get和post请求的是同一张验证码下面是我的代码publicclassImitateLogin{privateBufferedImageimg;privateStringpicName="pic\"+"pic.jpg";privateStringpath="D:\tesseract-ocr\Tesseract-OCR\doc\pic.jpg";privateStringtext;privateStringgetCookies;@SuppressWarnings("deprecation")@Testpublicvoidlogin()throwsHttpException,IOException{HttpClienthttpClient=newHttpClient();//设置cookie策略httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);httpClient.getParams().setParameter("http.protocol.single-cookie-header",true);//发送登录请求GetMethodgetMethod=newGetMethod("http://libertagia.com/pages/captcha?"+Math.random());getMethod.setRequestHeader("User-Agent","Mozilla/5.0(WindowsNT6.1;WOW64;rv:11.0)Gecko/20100101Firefox/11.0");getMethod.setRequestHeader("Host","libertagia.com");getMethod.setRequestHeader("Connection","Keep-Alive");getMethod.setRequestHeader("Accept","image/png,image/*;q=0.8,*/*;q=0.5");try{//发送请求intstatusCode=httpClient.executeMethod(getMethod);//响应错误if(statusCode!=HttpStatus.SC_OK){System.err.println("Methodfailed:"+getMethod.getStatusLine());return;}Stringget=GetCookies(httpClient);System.out.println(get);InputStreaminputStream=getMethod.getResponseBodyAsStream();OutputStreamoutStream=newFileOutputStream(picName);IOUtils.copy(inputStream,outStream);outStream.close();}catch(Exceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}finally{//释放连接getMethod.releaseConnection();}//读取保存的验证码try{//去除背景色img=OCRUtil.removeBackground(picName);//进一步去除黑点BufferedImagepicture=OCRUtil.removeBlack(img);//保存验证码ImageIO.write(img,"JPG",newFile(path));//检索验证码text=OCRUtil.recognize(newFile(path));System.out.println(text);}catch(Exceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}PostMethodpostMethod=newPostMethod("http://libertagia.com/login");HttpMethodParamsparams=postMethod.getParams();params.setContentCharset("UTF-8");//设置编码//参数设置List<NameValuePair>nameValues=newArrayList<NameValuePair>();//设置参数列表nameValues.add(newNameValuePair("data[Member][email]","993214132@qq.com"));nameValues.add(newNameValuePair("data[Member][password]","65504821"));nameValues.add(newNameValuePair("data[Captcha][captcha]",text));//头设置List<Header>headers=newArrayList<Header>();headers.add(newHeader("User-Agent","Mozilla/4.0(compatible;MSIE7.0;WindowsNT5.1)"));headers.add(newHeader("Accept","text/html,application/xhtml+xml,*/*"));headers.add(newHeader("Referer","http://libertagia.com/login"));headers.add(newHeader("Connection","Keep-Alive"));headers.add(newHeader("Host","libertagia.com"));httpClient.getHostConfiguration().getParams().setParameter("http.default-headers",headers);postMethod.setRequestBody((NameValuePair[])nameValues.toArray(newNameValuePair[nameValues.size()]));//添加参数列表intc=httpClient.executeMethod(postMethod);System.out.println(c);}privatestaticStringGetCookies(HttpClientclient){Stringtmpcookies="";Cookie[]cookies=client.getState().getCookies();for(Cookiec:cookies){tmpcookies+=c.toString()+";";}returntmpcookies;}}publicclassOCRUtil{privatestaticfinalStringEOL=System.getProperty("line.separator");publicstaticBufferedImageremoveBackground(Stringfile)throwsIOException{Filef=newFile(file);BufferedImageimg=ImageIO.read(f);intwidth=img.getWidth();intheight=img.getHeight();for(intx=0;x<width;++x){for(inty=0;y<height;++y){if(isWhite(img.getRGB(x,y))==1){img.setRGB(x,y,Color.WHITE.getRGB());}else{img.setRGB(x,y,Color.BLACK.getRGB());}}}returnimg;}privatestaticintisWhite(intrgb){Colorcolor=newColor(rgb);if(color.getRed()+color.getBlue()+color.getGreen()>=550){return1;}return0;}publicstaticBufferedImageremoveBlack(BufferedImageimg)throwsException{intwidth=img.getWidth();intheight=img.getHeight();for(intx=0;x<width;x++){b:for(inty=0;y<height;y++){intrgb=img.getRGB(x,y);if(getColorRGB(rgb)<100){intright,left,top,below;//取周圍的圖形rgbif(x>0&&y>0){if(x+1<=width-1){right=img.getRGB(x+1,y);left=img.getRGB(x-1,y);}else{break;}if(y+1<=height-1){top=img.getRGB(x,y+1);below=img.getRGB(x,y-1);}else{breakb;}if(getColorRGB(right)<100|getColorRGB(left)<100|getColorRGB(top)<100|getColorRGB(below)<100){img.setRGB(x,y,Color.BLACK.getRGB());}else{img.setRGB(x,y,Color.WHITE.getRGB());}right=0;left=0;top=0;below=0;}}}}returnimg;}privatestaticintgetColorRGB(intrgb){Colorcolor=newColor(rgb);returncolor.getRed()+color.getBlue()+color.getGreen();}publicstaticStringrecognize(FileimageFile)throwsException{FileoutputFile=newFile(imageFile.getParentFile(),"output");StringBufferstrB=newStringBuffer();List<String>cmd=newArrayList<String>();cmd.add("tesseract");cmd.add(imageFile.getName()+"");cmd.add(outputFile.getName());ProcessBuilderpb=newProcessBuilder();pb.directory(imageFile.getParentFile());cmd.set(1,imageFile.getName());pb.command(cmd);pb.redirectErrorStream(true);Processprocess=pb.start();intw=process.waitFor();//deletetempworkingfiles//imageFile.delete();if(w==0){//0代表正常退出BufferedReaderin=newBufferedReader(newInputStreamReader(newFileInputStream(outputFile.getAbsolutePath()+".txt"),"UTF-8"));Stringstr;while((str=in.readLine())!=null){strB.append(str).append(EOL);}in.close();}else{Stringmsg;switch(w){case1:msg="Errorsaccessingfiles.Theremaybespacesinyourimage'sfilename.";break;case29:msg="Cannotrecognizetheimageoritsselectedregion.";break;case31:msg="Unsupportedimageformat.";break;default:msg="Errorsoccurred.";}thrownewRuntimeException(msg);}//newFile(outputFile.getAbsolutePath()+".txt").delete();Stringtext=strB.toString();char[]c=text.toCharArray();Stringpattern=";:,'‘?$@-."?_~—/<’][";for(inti=0;i<c.length;i++){if(pattern.contains(c[i]+"")){c[i]='';}}Stringstring=newString(c);Stringt=string.replaceAll("\s{1,}","");returnt.toLowerCase().trim();}}
解决方案
解决方案二:
发代码不用格式化工具,没法看