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();
}
上一篇:Redhat终端中文乱码解决


下一篇:Apache Commons 常用工具类整理