81,094
社区成员
发帖
与我相关
我的任务
分享
public class test {
public static final DefaultHttpClient hc;
public static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36";
public static final CookieStore cookieStore;
static{
PoolingClientConnectionManager tsccm = new PoolingClientConnectionManager();
HttpParams params = new BasicHttpParams();
HttpProtocolParamBean paramBean = new HttpProtocolParamBean(params);
paramBean.setContentCharset("UTF-8");
paramBean.setUseExpectContinue(true);
paramBean.setUserAgent(USER_AGENT);
paramBean.setVersion(HttpVersion.HTTP_1_1);
hc = new DefaultHttpClient(tsccm, params);
tsccm.setMaxTotal(100);
cookieStore = new BasicCookieStore();
hc.setCookieStore(cookieStore);
}
public static void main(String[] args) throws Exception {
//get验证码并下载到本地磁盘
byte[] temp = getValidateCode();
byte2image(temp);
//在命令行输入验证码
Scanner sca=new Scanner(System.in);
String cCode=sca.next();
System.out.println(get(cCode));
}
//get body
public static String get(String code) {
String body = null;
//构造请求地址
String url="http://www.***.com/query?id=123&password=123&rand="+code;
try {
// Get请求
HttpGet httpget = new HttpGet(url);
HttpResponse httpresponse = hc.execute(httpget);
// 获取返回数据
HttpEntity entity = httpresponse.getEntity();
body = EntityUtils.toString(entity);
if (entity != null) {
entity.consumeContent();
}
} catch (ParseException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return body;
}
//get验证码
public static byte[] getValidateCode() {
byte[] cCode = null ;
try {
// Get请求
HttpGet httpget = new HttpGet("http://query.5184.com/query/image.jsp");
HttpResponse httpresponse = hc.execute(httpget);
HttpEntity entity = httpresponse.getEntity();
cCode = EntityUtils.toByteArray(entity);
if (entity != null) {
entity.consumeContent();
}
} catch (ParseException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return cCode;
}
//下载验证码
public static void byte2image(byte[] data){
String path ="C:/1.jpg";
if(data.length<3||path.equals("")) return;
try{
FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
imageOutput.write(data, 0, data.length);
imageOutput.close();
System.out.println("Make Picture success,Please find image in " + path);
} catch(Exception ex) {
System.out.println("Exception: " + ex);
ex.printStackTrace();
}
}
}