org.apache.commons.httpclient工具类(封装的HttpUtil)
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.contrib.ssl.AuthSSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.io.IOUtils; public class HttpFixture {
protected String url = null;
protected Map<String, String> paramlist = new HashMap();
protected Map<String, String> headerlist = new HashMap();
protected int status = 0;
protected byte[] responseBody = null;
protected String Body = "";
protected Header[] headers = null;
protected int fileno = 1;
protected String requestbody = "";
protected String encode = "utf-8";
private HttpClient client = null;
protected int requesttimeout = 120000;
protected int connecttimeout = 20000;
private boolean DoAuth = false;
private boolean mutualAuth = false;
private boolean isFileUpload = false;
private List<Part> multiRequestList = new ArrayList();
private boolean canAutoJump = false; public void setRequesttimeout(int time) {
this.requesttimeout = time;
} public void setConnecttimeout(int time) {
this.connecttimeout = time;
} public boolean isFileUpload() {
return this.isFileUpload;
} public void setFileUpload(boolean isFileUpload) {
this.isFileUpload = isFileUpload;
} public HttpClient getClient() {
return this.client;
} public void setClient(HttpClient client) {
this.client = client;
} public void setCanAutoJump(boolean canAutoJump) {
this.canAutoJump = canAutoJump;
} public int getStatus() {
return this.status;
} public void nextRequest() {
this.url = null;
this.paramlist = new HashMap();
this.status = 0;
this.responseBody = null;
this.Body = "";
this.headers = null;
this.requestbody = "";
this.isFileUpload = false;
this.multiRequestList = new ArrayList();
} public void clearDefinedheaders() {
this.headerlist = new HashMap();
} public HttpFixture() {
this.client = new HttpClient(new MultiThreadedHttpConnectionManager());
} public HttpFixture(String authip, int autport, String creuser, String crepass) {
this.client = new HttpClient();
this.client.getState().setCredentials(new AuthScope(authip, autport), new UsernamePasswordCredentials(creuser, crepass));
this.DoAuth = true;
} public HttpFixture(String authip, int autport, String sslVersion) {
this.client = new HttpClient();
this.setSslVerion();
} public void setSslVerion() {
String scheme = "https";
Protocol baseHttps = Protocol.getProtocol(scheme);
NewSSLSocketFactory newSSLSocketFactory = new NewSSLSocketFactory();
newSSLSocketFactory.setSslVersion("TLSv1.2");
Protocol authhttps = new Protocol(scheme, newSSLSocketFactory, 443);
Protocol.registerProtocol(scheme, authhttps);
} public void setUrl(String url) {
this.url = url;
} public HttpFixture(String authip, int autport, String creuser, String crepass, URL keystore, String keystorepass, URL trustkeystore, String trustkeystorepass) {
this.client = new HttpClient();
this.setSslVerion();
this.client.getParams().setAuthenticationPreemptive(true);
this.client.getState().setCredentials(new AuthScope(authip, autport), new UsernamePasswordCredentials(creuser, crepass));
Protocol authhttps = new Protocol("https", new AuthSSLProtocolSocketFactory(keystore, keystorepass, trustkeystore, trustkeystorepass), autport);
Protocol.registerProtocol("https", authhttps);
this.DoAuth = true;
this.mutualAuth = true;
} public void setEncode(String encode) {
this.encode = encode;
} public void addParamValue(String paramname, String value) {
try {
if (!this.isFileUpload) {
if (paramname.length() != paramname.getBytes().length && value.length() != value.getBytes().length) {
this.requestbody = this.requestbody + URLEncoder.encode(paramname, this.encode) + "=" + URLEncoder.encode(value, this.encode) + "&";
} if (paramname.length() == paramname.getBytes().length && value.length() != value.getBytes().length) {
this.requestbody = this.requestbody + paramname + "=" + URLEncoder.encode(value, this.encode) + "&";
} if (paramname.length() != paramname.getBytes().length && value.length() == value.getBytes().length) {
this.requestbody = this.requestbody + URLEncoder.encode(paramname, this.encode) + "=" + value + "&";
} if (paramname.length() == paramname.getBytes().length && value.length() == value.getBytes().length) {
this.requestbody = this.requestbody + paramname + "=" + value + "&";
}
} else {
this.multiRequestList.add(new StringPart(paramname, value, this.encode));
}
} catch (UnsupportedEncodingException var4) {
var4.printStackTrace();
} } public void addFileParamValue(String paramname, String filePath) {
try {
this.multiRequestList.add(new FilePart(paramname, new File(filePath)));
} catch (FileNotFoundException var4) {
var4.printStackTrace();
} } public void addParamValue2(String paramname, String value) {
try {
this.requestbody = this.requestbody + URLEncoder.encode(paramname, this.encode) + "=" + URLEncoder.encode(value, this.encode) + "&";
} catch (UnsupportedEncodingException var4) {
var4.printStackTrace();
} } public void addHeaderValue(String headername, String headervalue) {
this.headerlist.put(headername, headervalue);
} public String getHeaderValue(String headername) {
return (String)this.headerlist.get(headername);
} public void addRequestBody(String reqbody) {
this.requestbody = this.requestbody + reqbody;
} public String getResponseheader(String headername) {
Header[] var5 = this.headers;
int var4 = this.headers.length; for(int var3 = 0; var3 < var4; ++var3) {
Header header = var5[var3];
if (header.getName().equals(headername)) {
return header.getValue();
}
} return "";
} public String getResponseheaders() {
String headerstr = "";
Header[] var5 = this.headers;
int var4 = this.headers.length; for(int var3 = 0; var3 < var4; ++var3) {
Header header = var5[var3];
headerstr = headerstr + header.getName() + "=" + header.getValue() + ";";
} return headerstr;
} public void Get() {
String paramstring;
if (!this.url.contains("?")) {
paramstring = this.url + "?";
} else {
paramstring = this.url + "&";
} paramstring = paramstring + this.requestbody;
GetMethod method = new GetMethod(paramstring);
if (this.DoAuth) {
method.setDoAuthentication(this.DoAuth);
} method.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler());
method.getParams().setParameter("http.socket.timeout", this.requesttimeout);
this.client.getHttpConnectionManager().getParams().setConnectionTimeout(this.connecttimeout);
Iterator iter1 = this.headerlist.entrySet().iterator(); while(iter1.hasNext()) {
Entry entry = (Entry)iter1.next(); try {
method.addRequestHeader((String)entry.getKey(), (String)entry.getValue());
} catch (Exception var13) {
var13.printStackTrace();
}
} try {
this.status = this.client.executeMethod(method);
this.responseBody = IOUtils.toByteArray(method.getResponseBodyAsStream());
this.headers = method.getResponseHeaders();
this.Body = new String(this.responseBody, this.encode);
} catch (HttpException var10) {
var10.printStackTrace();
} catch (IOException var11) {
var11.printStackTrace();
} finally {
method.releaseConnection();
} } public void Post() {
if (this.url.startsWith("https") && !this.mutualAuth) {
this.setSslVerion();
} PostMethod method = new PostMethod(this.url);
if (this.DoAuth) {
method.setDoAuthentication(this.DoAuth);
} method.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler());
method.getParams().setParameter("http.socket.timeout", this.requesttimeout);
this.client.getHttpConnectionManager().getParams().setConnectionTimeout(this.connecttimeout);
String newuri;
if (!this.isFileUpload) {
Iterator iter1 = this.headerlist.entrySet().iterator(); while(iter1.hasNext()) {
Entry entry = (Entry)iter1.next(); try {
method.addRequestHeader((String)entry.getKey(), (String)entry.getValue());
} catch (Exception var12) {
var12.printStackTrace();
}
} try {
newuri = "";
if (this.getHeaderValue("contentType") != null) {
newuri = this.getHeaderValue("contentType");
} StringRequestEntity a1 = new StringRequestEntity(this.requestbody, newuri, this.encode);
method.setRequestEntity(a1);
} catch (UnsupportedEncodingException var11) {
var11.printStackTrace();
}
} else {
Part[] parts = (Part[])this.multiRequestList.toArray(new Part[this.multiRequestList.size()]);
MultipartRequestEntity mre = new MultipartRequestEntity(parts, method.getParams());
method.setRequestEntity(mre);
} try {
this.status = this.client.executeMethod(method);
this.responseBody = IOUtils.toByteArray(method.getResponseBodyAsStream());
this.headers = method.getResponseHeaders();
this.Body = new String(this.responseBody, this.encode);
if (this.status != 200) {
while(true) {
while(this.canAutoJump && this.status == 302 || this.status == 301 || this.status == 303 || this.status == 307) {
Header header = method.getResponseHeader("location");
System.out.println("获取到跳转header>>>" + header);
if (header != null) {
newuri = header.getValue();
if (newuri == null || newuri.equals("")) {
newuri = "/";
} GetMethod redirect = new GetMethod(newuri);
this.status = this.client.executeMethod(redirect);
System.out.println("Redirect:" + redirect.getStatusLine().toString());
this.responseBody = IOUtils.toByteArray(redirect.getResponseBodyAsStream());
this.headers = redirect.getResponseHeaders();
this.Body = new String(this.responseBody, this.encode);
} else {
System.out.println("Invalid redirect");
}
} return;
}
}
} catch (HttpException var13) {
var13.printStackTrace();
} catch (IOException var14) {
var14.printStackTrace();
} finally {
method.releaseConnection();
} } public boolean saveResponse2File(String filename) throws FileNotFoundException {
Date dateNow = new Date();
String[] filepath = filename.split("\\\\");
String filep = ""; for(int i = 0; i < filepath.length - 1; ++i) {
filep = filep + filepath[i] + "\\";
} File path = new File(filep);
if (!path.isDirectory()) {
path.mkdir();
} SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
String dateNowStr = dateFormat.format(dateNow);
FileOutputStream fis = new FileOutputStream(filename + dateNowStr + this.fileno + ".html", true);
++this.fileno; try {
fis.write(this.responseBody);
} catch (Exception var11) {
var11.printStackTrace();
return false;
} try {
fis.close();
return true;
} catch (IOException var10) {
var10.printStackTrace();
return false;
}
} public boolean findFileStringinResponse(String filename) {
BufferedInputStream bufferedInputStream = null; try {
File file = new File(filename);
if (filename == null || filename.equals("")) {
throw new NullPointerException("无效的文件路径");
} long len = file.length();
byte[] bytes = new byte[(int)len];
bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
int r = bufferedInputStream.read(bytes);
if ((long)r != len) {
throw new IOException("读取文件不正确");
} bufferedInputStream.close();
String content = new String(bytes, this.encode);
if (content.equals("MYHTTPCLIENT_ZERORESPONSE")) {
boolean kongresult = this.responseBody.length == 0;
boolean var14 = this.responseBody.length == 0;
return var14;
} try {
byte[] des = bytes;
int a = 0; while(a < this.responseBody.length - des.length + 1) {
boolean result = true;
int b = 0; while(true) {
if (b < des.length) {
if (this.responseBody[a + b] == des[b]) {
++b;
continue;
} result = false;
} if (result) {
return true;
} ++a;
break;
}
}
} catch (Exception var27) {
var27.printStackTrace();
}
} catch (FileNotFoundException var28) {
var28.printStackTrace();
return false;
} catch (IOException var29) {
var29.printStackTrace();
return false;
} finally {
try {
bufferedInputStream.close();
} catch (IOException var26) {
var26.printStackTrace();
return false;
}
} return false;
} public boolean FileMatchResponse(String filename) {
BufferedInputStream bufferedInputStream = null; try {
File file = new File(filename);
if (filename != null && !filename.equals("")) {
long len = file.length();
byte[] bytes = new byte[(int)len];
bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
int r = bufferedInputStream.read(bytes);
if ((long)r != len) {
throw new IOException("读取文件不正确");
} bufferedInputStream.close();
String content = new String(bytes, this.encode);
boolean var12;
if (content.equals("MYHTTPCLIENT_ZERORESPONSE")) {
var12 = this.responseBody.length == 0;
return var12;
} String responseaim = new String(this.responseBody, this.encode);
boolean matchresult = responseaim.matches(content);
var12 = matchresult;
return var12;
} throw new NullPointerException("无效的文件路径");
} catch (FileNotFoundException var23) {
var23.printStackTrace();
} catch (IOException var24) {
var24.printStackTrace();
return false;
} finally {
try {
bufferedInputStream.close();
} catch (IOException var22) {
var22.printStackTrace();
return false;
}
} return false;
} public boolean ResponseMatch(String content) {
if (content.equals("MYHTTPCLIENT_ZERORESPONSE")) {
boolean kongresult = this.responseBody.length == 0;
return kongresult;
} else {
try {
String responseaim = new String(this.responseBody, this.encode);
boolean result = responseaim.matches(content);
return result;
} catch (Exception var4) {
var4.printStackTrace();
return false;
}
}
} public boolean findStringinResponse(String content) {
if (content.equals("MYHTTPCLIENT_ZERORESPONSE")) {
return this.responseBody.length == 0;
} else {
try {
byte[] des = content.getBytes(this.encode); for(int a = 0; a < this.responseBody.length - des.length + 1; ++a) {
boolean result = true; for(int b = 0; b < des.length; ++b) {
if (this.responseBody[a + b] != des[b]) {
result = false;
break;
}
} if (result) {
return true;
}
}
} catch (UnsupportedEncodingException var6) {
var6.printStackTrace();
} return false;
}
} public int findNumberofStringinResponse(String content) {
if (content != null && !content.equals("")) {
int count = 0; try {
byte[] des = content.getBytes(this.encode); for(int a = 0; a < this.responseBody.length - des.length + 1; ++a) {
boolean result = true; for(int b = 0; b < des.length; ++b) {
if (this.responseBody[a + b] != des[b]) {
result = false;
break;
}
} if (result) {
++count;
}
}
} catch (UnsupportedEncodingException var7) {
var7.printStackTrace();
} return count;
} else {
return 0;
}
} public String saveParamLeftstrRightstr(String leftstr, String rightstr) {
byte[] content = (byte[])null; try {
byte[] left = leftstr.getBytes(this.encode);
byte[] right = rightstr.getBytes(this.encode); for(int a = 0; a < this.responseBody.length - left.length - right.length + 1; ++a) {
boolean result = true; int a1;
for(a1 = 0; a1 < left.length; ++a1) {
if (this.responseBody[a + a1] != left[a1]) {
result = false;
break;
}
} if (result) {
int start = a + left.length; for(a1 = start; a1 < this.responseBody.length - right.length + 1; ++a1) {
boolean result2 = true; int j;
for(j = 0; j < right.length; ++j) {
if (this.responseBody[a1 + j] != right[j]) {
result2 = false;
break;
}
} if (result2) {
int end = a1 - 1;
if (start > end) {
return "";
} content = new byte[end - start + 1];
j = 0; for(int a2 = start; a2 <= end; ++a2) {
content[j] = this.responseBody[a2];
++j;
} String collstr = new String(content, this.encode);
return collstr;
}
}
}
}
} catch (UnsupportedEncodingException var14) {
;
} return "";
} public String getResponseBody() {
return this.Body;
}
}
maven依赖说明
commons-httpclient 是 apache-commons 项目下的一个子项目,后来被 HttpComponents 取代,后者提供了更好的性能和更大的灵活性。
commons-httpclient的GAV地址为
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
其最新版本为3.1,且已经不再更新;
HttpComponents的GAV地址为
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
实例:
public void login(HttpFixture request) {
Reporter.log("正在登录FSC系统...");
request.setUrl(this.loginUrl);
request.addHeaderValue("Content-Type", "application/x-www-form-urlencoded");
request.addParamValue("method", "login");
request.addParamValue("userName", this.username);
request.addParamValue("password", this.password);
request.addParamValue("tokenPWD", "");
request.Post();
request.nextRequest(); request.setUrl("http://fscposs.com/fscposs/ftl/fscposs/main.jsp");
request.Get(); if (request.findStringinResponse("欢迎登陆")) {
Reporter.log("登录FSC系统成功.");
} else {
Reporter.FALSE("登录FSC系统失败.");
}
request.nextRequest();
}
org.apache.commons.httpclient工具类(封装的HttpUtil)的更多相关文章
- org.apache.commons.httpclient工具类
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpcl ...
- Apache Commons 常用工具类整理
其实一直都在使用常用工具类,只是从没去整理过,今天空了把一些常用的整理一下吧 怎么使用的一看就明白,另外还有注释,最后的使用pom引入的jar包 public class ApacheCommonsT ...
- org.apache.httpcomponents:httpclient 工具类
基于httpclient 版本4.4.1 因为http连接需要三次握手,在需要频繁调用时浪费资源和时间 故采用连接池的方式连接 根据实际需要更改 连接池最大连接数.路由最大连接数 另一个需要注意的是 ...
- 转:轻松把玩HttpClient之封装HttpClient工具类(一)(现有网上分享中的最强大的工具类)
搜了一下网络上别人封装的HttpClient,大部分特别简单,有一些看起来比较高级,但是用起来都不怎么好用.调用关系不清楚,结构有点混乱.所以也就萌生了自己封装HttpClient工具类的想法.要做就 ...
- java apache commons HttpClient发送get和post请求的学习整理(转)
文章转自:http://blog.csdn.net/ambitiontan/archive/2006/01/06/572171.aspx HttpClient 是我最近想研究的东西,以前想过的一些应用 ...
- Java开发小技巧(五):HttpClient工具类
前言 大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具 ...
- 基于HttpClient4.5.2实现的HttpClient工具类
1.maven依赖: <dependency> <groupId>org.apache.commons</groupId> <artifactId>co ...
- flink---实时项目--day02-----1. 解析参数工具类 2. Flink工具类封装 3. 日志采集架构图 4. 测流输出 5. 将kafka中数据写入HDFS 6 KafkaProducer的使用 7 练习
1. 解析参数工具类(ParameterTool) 该类提供了从不同数据源读取和解析程序参数的简单实用方法,其解析args时,只能支持单只参数. 用来解析main方法传入参数的工具类 public c ...
- org.apache.commons.lang.StringUtils类
org.apache.commons.lang.StringUtils类 本文摘自:(http://www.blogjava.net/japper/archive/2012/05/23/378946. ...
随机推荐
- c# 第21节 方法声明和调用
本节内容: 1:为什么要有方法 2:方法的声明及使用 3:方法params 传入接收数组 4:值传递和引用传递 5:输出参数out 1:为什么要有方法 2:方法的声明及使用 声明实例: 3:方法par ...
- day71_10_16多表断关联
---恢复内容开始--- 本次环境: 配置settings INSTALLED_APPS = [ # ... 'rest_framework', ] DATABASES = { 'default': ...
- angular跳转和传参
使用routerLink跳转 <a routerLink=["/exampledetail",id]></a> <a routerLink=[&quo ...
- java1.8 AQS AbstractQueuedSynchronizer学习
AQS concurrent并发包中非常重要的顶层锁类,往往用的比较多的是ReentrantLock,然而ReentrantLock的实现依赖AbstractQueuedSynchronizer在到上 ...
- POJ 1094 (传递闭包 + 拓扑排序)
题目链接: POJ 1094 题目大意:有 1 ~ N 个大写字母,且从 A 开始依次 N 个.再给你 M 个小于的关系,比如 A < B ,让你判断三种可能: 1.在第 i 个关系罗列之后,是 ...
- Android系统之LK启动流程分析(一)
1.前言 LK是Little Kernel的缩写,在Qualcomm平台的Android系统中普遍采用LK作为bootloader,它是一个开源项目,LK是整个系统的引导部分,所以不是独立存在的,但是 ...
- Logstash处理数据用法示例---待完善
filter { mutate { rename => [ "message", "blog_html" ] copy => { "blo ...
- python常用库简单使用( PyPDF2 )
PyPDF2学习 1 这个模块的名字对大小写是敏感的,所以,确保y是小写的,其他字母都是大写的
- python验证码处理(1)
目录 一.普通图形验证码 这篇博客及之后的系列,我会向大家介绍各种验证码的识别.包括普通图形验证码,极验滑动验证码,点触验证码,微博宫格验证码. 一.普通图形验证码 之前的博客已向大家介绍了简 ...
- Winform中使用FastReport的PictureObject时通过代码设置图片源并使Image图片旋转90度
场景 FastReport安装包下载.安装.去除使用限制以及工具箱中添加控件: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/10 ...