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. mongodb数据库的存储问题

    MongoDB在Windows中默认的数据库目录是c:\data.如果在没有该目录的情况下,直接运行mongod.exe,就会报如下错误(并没有把mongodb设置为服务,所以通过命令行的形式启动,注 ...

  2. 各版本mysql修改root密码

    今天在安装mysql5.7.8的时候遇到一些问题,首当其冲便的是初始root密码的变更,特分享解决方法如下: 1.mysql5.7会生成一个初始化密码,而在之前的版本首次登陆不需要登录. shell& ...

  3. C++ class 中的 const 成员函数

    const 修饰的成员函数  表示  不会修改class中的成员变量. const 和 非-const 的成员函数同事存在时, 用户定义 const 类对象,调用 const 成员函数: 定义 非-c ...

  4. 浅谈C++ STL stack 容器

    浅谈C++ STL stack 容器 本篇随笔简单介绍一下\(C++STL\)中\(stack\)容器的使用方法和常见的使用技巧. stack容器的概念 \(stack\)在英文中是栈的意思.栈是一种 ...

  5. luoguP3346 [ZJOI2015]诸神眷顾的幻想乡

    题意 学习了广义后缀自动机. 广义后缀自动机与普通后缀自动机的区别在于它是对多个串建的,于是可以处理多个串. 广义后缀自动机和普通后缀自动机的区别在于两个特判,可以见这篇题解 对于这题,因为叶子数量小 ...

  6. <BackTracking> permutation 254 47 60

    254. Factor Combinations class Solution { public List<List<Integer>> getFactors(int n) { ...

  7. [LeetCode] 11. Container With Most Water 装最多水的容器

    Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). ...

  8. 第01组 Beta版本演示

    目录 1.1 本组成员 1.2 工作流程.组员分工.组员工作量比例 1.3 GitHub 项目链接 1.4 本组 Beta 冲刺站立会议博客链接汇总 1.5 燃尽图 1.6 原计划.达成情况及原因分析 ...

  9. decodeURIComponent 解码函数

    想象一个场景,你朋友发一个链接让你打开,但链接是下面其中之一,你会不会想锤死他 1. \u0068\u0074\u0074\u0070\u003a\u002f\u002f\u0062\u0069\u0 ...

  10. redis命令之 ----SortedSed(有序集合)

    ZADD ZADD key score member [[score member] [score member] ...] 将一个或多个 member 元素及其 score 值加入到有序集 key  ...