httpclient一个实现了HTTP协议的客户端编程工具包
一个使用的背景:登录需要验证,需要压力测试一下,用webdriver等工具搞不定
就用到了他,有ocr开源的工具,结合httpclient完美的处理了
网上的例子主要是3的版本,这里主要是总结一下4的版本
首先放几个例子这儿参考:
http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113252.html
http://blog.csdn.net/java2000_net/article/details/3720571
本身带的例子也不错:下载地址,api的参考
http://hc.apache.org/downloads.cgi
放一个例子这儿,自己参考:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet(
"http://10.101.2.13:28080/ECLink//rand.action");
HttpPost httpost = new HttpPost(
"http://10.101.2.13:28080/ECLink/user_validLogin.action");
try {
String yzm = "";
HttpResponse response = httpclient.execute(getMethod);
Header headers[] = response.getAllHeaders();
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
StringBuilder cookieValue = new StringBuilder();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
cookieValue.append(cookies.get(i).toString());
}
}
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
saveFile(instream, "2.bmp");
InputStream instream2 = new FileInputStream("2.bmp");
BufferedImage bi = ImageIO.read(instream2);
yzm = ImageRead.read(bi, 1);
System.out.println(yzm + "-----------------------------");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("userName", "admin"));
nvps.add(new BasicNameValuePair("password", "888888"));
nvps.add(new BasicNameValuePair("validCode", yzm));
httpost.setEntity(new UrlEncodedFormEntity(nvps));
response = httpclient.execute(httpost);
HttpEntity entity1 = response.getEntity();
if (entity1 != null) {
// System.out.println("Response content: " +
// inputStream2String(entity1.getContent()));
saveFile(entity1.getContent(), "3.html");
instream.close();
}
for (int i = 1; i <= 1; i++) {
List<NameValuePair> list1 = new ArrayList<NameValuePair>();
HttpPost httpost1 = new HttpPost("http://10.101.2.13:28080/ECLink/computerCheck_computerCheck.action");
list1.add(new BasicNameValuePair("sgid", sgid.trim()));
httpost1.getParams().setParameter("http.protocol.content-charset",HTTP.UTF_8);
httpost1.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
httpost1.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
httpost1.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);
httpost1.setEntity(new UrlEncodedFormEntity(list1,HTTP.UTF_8));
response = httpclient.execute(httpost1);
HttpEntity entity2 = response.getEntity();
if (entity2 != null) {
// System.out.println("Response content: " +
// inputStream2String(entity1.getContent()));
saveFile(entity2.getContent(), "408.html");
instream.close();
}
httpost1.abort();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpost.abort();
getMethod.abort();
}
对于大的表单,感觉也不是很方便,还是没有直接用自动测试工具方便
已有 0 人发表留言,猛击->> 这里<<-参与讨论
ITeye推荐