1 import java.awt.image.BufferedImage; 2 import java.io.InputStream; 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import javax.imageio.ImageIO; 7 8 import org.apache.http.Consts; 9 import org.apache.http.HttpEntity; 10 import org.apache.http.HttpResponse; 11 import org.apache.http.NameValuePair; 12 import org.apache.http.client.entity.UrlEncodedFormEntity; 13 import org.apache.http.client.methods.HttpGet; 14 import org.apache.http.client.methods.HttpPost; 15 import org.apache.http.cookie.Cookie; 16 import org.apache.http.impl.client.DefaultHttpClient; 17 import org.apache.http.message.BasicNameValuePair; 18 import org.apache.http.util.EntityUtils; 19 20 import com.asprise.util.ocr.OCR; 21 22 /** 23 * @title: test2.java 24 * @package 25 * @description: TODO 26 * @author caiyigo 27 * @date 2012-9-15 下午9:17:59 28 * @version v1.00 29 */ 30 31 public class test2 { 32 public static void main(String[] args) throws Exception { 33 34 DefaultHttpClient httpclient = new DefaultHttpClient(); 35 try { 36 HttpGet httpget = new HttpGet( 37 "http://query.5184.com/query/image.jsp"); 38 39 HttpResponse response = httpclient.execute(httpget); 40 HttpEntity entity = response.getEntity(); 41 System.out.println("获取验证码: " + response.getStatusLine()); 42 /* System.out.println(EntityUtils.toString(entity)); */ 43 InputStream is = entity.getContent(); 44 BufferedImage image = ImageIO.read(is); 45 String imgcode = new OCR().recognizeEverything(image); 46 47 System.out.println("\n---- 验证码是: ------- \n" + imgcode); 48 49 HttpPost httpost = new HttpPost( 50 "http://query.5184.com/query/zk/zk_seat_2012_07.jsp"); 51 52 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); 53 nvps.add(new BasicNameValuePair("name0", "010211201317")); 54 nvps.add(new BasicNameValuePair("rand", imgcode)); 55 nvps.add(new BasicNameValuePair("serChecked", "on")); 56 httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); 57 58 response = httpclient.execute(httpost); 59 entity = response.getEntity(); 60 System.out.println(EntityUtils.toString(entity)); 61 System.out.println("返回: " + response.getStatusLine()); 62 63 System.out.println(response.getProtocolVersion()); 64 65 System.out.println(response.getStatusLine().getStatusCode()); 66 67 System.out.println(response.getStatusLine().getReasonPhrase()); 68 69 EntityUtils.consume(entity); 70 71 } finally { 72 73 httpclient.getConnectionManager().shutdown(); 74 } 75 } 76 }
验证码识别后多了一个空格
请问楼主的问题解决了吗?求解。。。
猜测是httpclient没有处理cookie,“获取验证码”和“登录”两次提交的cookie不同(或者没有提交cookie),服务器认为是两次独立的请求,所以验证码校验失败吧。
只是猜测,建议用Fiddler工具抓包看看就知道了。
很显然是没有处理cookie,因为请求验证码和post数据两次不是一次请求,要带会话信息sessionid