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)的更多相关文章

  1. org.apache.commons.httpclient工具类

    import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpcl ...

  2. Apache Commons 常用工具类整理

    其实一直都在使用常用工具类,只是从没去整理过,今天空了把一些常用的整理一下吧 怎么使用的一看就明白,另外还有注释,最后的使用pom引入的jar包 public class ApacheCommonsT ...

  3. org.apache.httpcomponents:httpclient 工具类

    基于httpclient 版本4.4.1 因为http连接需要三次握手,在需要频繁调用时浪费资源和时间 故采用连接池的方式连接 根据实际需要更改  连接池最大连接数.路由最大连接数 另一个需要注意的是 ...

  4. 转:轻松把玩HttpClient之封装HttpClient工具类(一)(现有网上分享中的最强大的工具类)

    搜了一下网络上别人封装的HttpClient,大部分特别简单,有一些看起来比较高级,但是用起来都不怎么好用.调用关系不清楚,结构有点混乱.所以也就萌生了自己封装HttpClient工具类的想法.要做就 ...

  5. java apache commons HttpClient发送get和post请求的学习整理(转)

    文章转自:http://blog.csdn.net/ambitiontan/archive/2006/01/06/572171.aspx HttpClient 是我最近想研究的东西,以前想过的一些应用 ...

  6. Java开发小技巧(五):HttpClient工具类

    前言 大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具 ...

  7. 基于HttpClient4.5.2实现的HttpClient工具类

    1.maven依赖: <dependency> <groupId>org.apache.commons</groupId> <artifactId>co ...

  8. flink---实时项目--day02-----1. 解析参数工具类 2. Flink工具类封装 3. 日志采集架构图 4. 测流输出 5. 将kafka中数据写入HDFS 6 KafkaProducer的使用 7 练习

    1. 解析参数工具类(ParameterTool) 该类提供了从不同数据源读取和解析程序参数的简单实用方法,其解析args时,只能支持单只参数. 用来解析main方法传入参数的工具类 public c ...

  9. org.apache.commons.lang.StringUtils类

    org.apache.commons.lang.StringUtils类 本文摘自:(http://www.blogjava.net/japper/archive/2012/05/23/378946. ...

随机推荐

  1. Vue介绍(一)

    官网:https://cn.vuejs.org/ Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架.与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用.V ...

  2. LG2495 「SDOI2011」消耗战 虚树

    问题描述 LG2495 题解 虚树 \(\mathrm{Code}\) #include<bits/stdc++.h> using namespace std; #define int l ...

  3. html头部标签汇总

    <!DOCTYPE html> <!-- 使用 HTML5 doctype,不区分大小写 --> <html lang="zh-cmn-Hans"&g ...

  4. 2019 SDN上机第三次作业

    2019 SDN上机第三次作业 实验一 利用Mininet仿真平台构建如下图所示的网络拓扑,配置主机h1和h2的IP地址(h1:10.0.0.1,h2:10.0.0.2),测试两台主机之间的网络连通性 ...

  5. Class的使用,构造方法,实例属性和实例方法,静态属性和静态方法,this和super关键字,类的继承

    s6新增了一种定义对象实例的方法,Class(类)这个概念,作为对象的模板.class可以看作只是一个语法糖,通过class关键字,可以定义类.让对象原型的写法更加清晰.更像面向对象编程的语法. 一. ...

  6. C语言中关于输出n个数后就换行的问题。

    例如:n=10 ........; n++; if(n%10==0&&n!=0)    //因为当n=0时,n%10的值也是0,就也会转行,为了防止这种情况的发生,就用了&&a ...

  7. CSS使用知识点

    1.空白符   2.字符间距   3.省略号样式   4.水平垂直居中用法   5.CSS角标实现   空格符 1.  相当于键盘按下的空格,区别是 是可以累加的空格,键盘敲下的空格不会累加 2.  ...

  8. Git修改和配置用户名和邮箱

    git在push/push to时需要使用到user.name和user.email,切记一定要现配置好查看user.name/user.email git config user.name git ...

  9. win10 mysql5.7.28 配置安装

    如果有服务,使用下面命令删除,管理员身份打开cmd : sc delete mysql 1.下载 https://dev.mysql.com/downloads/mysql/5.7.html 没有的O ...

  10. 【Linux命令】Linux命令后面所接选项和参数的区别

    Linux命令后面所接选项和参数的区别 在使用Linux命令时,有时候后面会跟一些"选项"(options)或"参数"(agruments) 命令格式为: #中 ...