- 浏览: 80285 次
- 性别:
- 来自: 北京
文章分类
最新评论
http://blog.csdn.net/lovingprince/archive/2009/09/03/4516532.aspx
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(1, true));
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.Cookie;
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.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.FileCopyUtils;
/**
* 处理HTTPS和HTTP登陆.
*
* @author gareth liao
*
*/
public class HttpsLogin {
/**
* location.
*/
public static final String LOCATION = "location";
/**
* session id.
*/
public static final String SESSION_ID = "PHPSESSID";
/**
* http 协议开头.
*/
public static final String HTTP_HEAD = "http://";
private static final Log log = LogFactory.getLog(HttpsLogin.class);
/**
* HttpClient 对象.
*/
private HttpClient httpClient = null;
/**
* web 上下文路径.
*/
private String path = null;
/**
* 登录信息.
*/
private LoginInfs loginInfs = null;
public HttpsLogin(LoginInfs loginInfs, String path) {
httpClient = new HttpClient();
this.path = path;
this.loginInfs = loginInfs;
}
private String getLogonSite(boolean isHttps) {
String head = isHttps ? Constants.HTTPSOTHER : HTTP_HEAD;
return head + loginInfs.getIpAddr() + loginInfs.getLoginPath();
}
public Map<String, Object> handleHttpsLogin(String olduri, boolean isHttps) {
Map<String, Object> logonInfos = null;
String logonSite = getLogonSite(isHttps);
int logonPort = loginInfs.getPort();
if (isHttps) {
Protocol myhttps = new Protocol(Constants.HTTPS,
new MySecureProtocolSocketFactory(), logonPort);
Protocol.registerProtocol(Constants.HTTPS, myhttps);
}
if (loginInfs.getFlag().equals(Constants.SINGLE_FLAG)) {
logonInfos = handleSingleManage(olduri);
}
if (logonInfos == null) {
PostMethod postMethod = setPostRequestInfos(logonSite);
String newuri = path + Constants.ERROR_PAGE;
try {
httpClient.executeMethod(postMethod);
logonInfos = getLocation(postMethod, path);
} catch (Exception e) {
logonInfos = new HashMap<String, Object>();
logonInfos.put(loginInfs.getUrl(), newuri);
log.error("network errors or device service stop.");
} finally {
postMethod.releaseConnection();
}
}
return logonInfos;
}
/**
* 处理单机登录,避免重复登录.
*
* @param olduri
* @return
*/
private Map<String, Object> handleSingleManage(String olduri) {
Map<String, Object> logonInfos = null;
int statecode = HttpStatus.SC_BAD_REQUEST;
if ((olduri != null) && (olduri.indexOf(loginInfs.getIpAddr()) != -1)) {
GetMethod getmethod = new GetMethod(olduri);
getmethod.setDoAuthentication(true);
try {
httpClient.executeMethod(getmethod);
// 因为getmethod.getResponseBodyAsString()有bug. 故采用此方法.
InputStream input = getmethod.getResponseBodyAsStream();
if (input != null && input.available() > 0) {
byte[] b = FileCopyUtils.copyToByteArray(input);
String datas = new String(b);
if (datas != null && datas.length() > 0
&& datas.indexOf(Constants.FRAME_SET) != -1)
statecode = HttpStatus.SC_OK;
}
} catch (HttpException e) {
log.error("network errors or device service stop.");
} catch (IOException e) {
log.error("network errors or device service stop.");
} finally {
getmethod.releaseConnection();
}
}
if (statecode == HttpStatus.SC_OK) {
logonInfos = new HashMap<String, Object>();
logonInfos.put(Constants.STATECODE, HttpStatus.SC_OK);
logonInfos.put(loginInfs.getUrl(), olduri);
}
return logonInfos;
}
/**
* 设置登录信息.
*
* @param logonSite
* @return
*/
private PostMethod setPostRequestInfos(String logonSite) {
PostMethod postMethod = new PostMethod(logonSite);
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(1, true));
String username = loginInfs.getUserName();
String pwd = loginInfs.getPassword();
NameValuePair userid = new NameValuePair(
loginInfs.getUser_name_param(), username);
NameValuePair password = new NameValuePair(loginInfs
.getUser_pwd_param(), pwd);
NameValuePair[] all = null;
if (Constants.MANAGER_FLAG.equals(loginInfs.getFlag())) {
all = new NameValuePair[] { userid, password,
new NameValuePair("mngip", "127.0.0.1"),
new NameValuePair("mngport", "" + Constants.PHPCOMM_PORT) };
} else {
all = new NameValuePair[] { userid, password };
}
postMethod.setRequestBody(all);
return postMethod;
}
private Map<String, Object> getLocation(PostMethod post, String path) {
Map<String, Object> backInfos = new HashMap<String, Object>();
String newuri = path + Constants.ERROR_PAGE;
int statuscode = post.getStatusCode();
if (isSuccess(statuscode)) {
newuri = getLocation(post);
Cookie[] logoncookies = httpClient.getState().getCookies();
Map<String, String> cookieInfos = getCookiesInfos(logoncookies);
newuri = newuri + "?" + SESSION_ID + "="
+ cookieInfos.get(SESSION_ID);
backInfos.put(SESSION_ID, cookieInfos.get(SESSION_ID));
if (loginInfs.getUrl().equals(Constants.MANAGER_OLD_URL)) {
newuri += Constants.MOCKDEV;
}
int bindex = newuri.indexOf(loginInfs.getIpAddr())
+ loginInfs.getIpAddr().length();
String firpart = newuri.substring(0, bindex);
String secpart = newuri.substring(bindex);
newuri = firpart + ":" + loginInfs.getPort() + secpart;
backInfos.put(loginInfs.getUrl(), newuri);
backInfos.put(Constants.STATECODE, HttpStatus.SC_OK);
}
return backInfos;
}
/**
* 检测返回的状态码.
*
* @param statusCode
* @return
*/
private boolean isSuccess(int statusCode) {
boolean isSuccess = false;
int[] codes = { HttpStatus.SC_MOVED_TEMPORARILY,
HttpStatus.SC_MOVED_PERMANENTLY, HttpStatus.SC_SEE_OTHER,
HttpStatus.SC_TEMPORARY_REDIRECT };
for (int index = 0; index < codes.length; index++) {
if (statusCode == codes[index]) {
isSuccess = true;
break;
}
}
return isSuccess;
}
/**
* 过滤cookie, 取得SESSION_ID所在cookie的信息.
*
* @param logoncookies
* Cookie[]
* @return cookie Map<String, String>
*/
private Map<String, String> getCookiesInfos(Cookie[] logoncookies) {
Map<String, String> cookie = new HashMap<String, String>();
for (int index = 0; index < logoncookies.length; index++) {
String name = logoncookies[index].getName();
if (name.equalsIgnoreCase(SESSION_ID)) {
cookie.put(SESSION_ID, logoncookies[index].getValue().trim());
break;
}
}
return cookie;
}
/**
* 取得uri.
*
* @param post
* @return
*/
private String getLocation(PostMethod post) {
String uri = null;
Header redirect = post.getResponseHeader(LOCATION);
if (redirect != null) {
uri = redirect.getValue();
if (StringUtil.isEmpty(uri))
uri = "/";
}
return uri;
}
}
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(1, true));
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.Cookie;
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.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.FileCopyUtils;
/**
* 处理HTTPS和HTTP登陆.
*
* @author gareth liao
*
*/
public class HttpsLogin {
/**
* location.
*/
public static final String LOCATION = "location";
/**
* session id.
*/
public static final String SESSION_ID = "PHPSESSID";
/**
* http 协议开头.
*/
public static final String HTTP_HEAD = "http://";
private static final Log log = LogFactory.getLog(HttpsLogin.class);
/**
* HttpClient 对象.
*/
private HttpClient httpClient = null;
/**
* web 上下文路径.
*/
private String path = null;
/**
* 登录信息.
*/
private LoginInfs loginInfs = null;
public HttpsLogin(LoginInfs loginInfs, String path) {
httpClient = new HttpClient();
this.path = path;
this.loginInfs = loginInfs;
}
private String getLogonSite(boolean isHttps) {
String head = isHttps ? Constants.HTTPSOTHER : HTTP_HEAD;
return head + loginInfs.getIpAddr() + loginInfs.getLoginPath();
}
public Map<String, Object> handleHttpsLogin(String olduri, boolean isHttps) {
Map<String, Object> logonInfos = null;
String logonSite = getLogonSite(isHttps);
int logonPort = loginInfs.getPort();
if (isHttps) {
Protocol myhttps = new Protocol(Constants.HTTPS,
new MySecureProtocolSocketFactory(), logonPort);
Protocol.registerProtocol(Constants.HTTPS, myhttps);
}
if (loginInfs.getFlag().equals(Constants.SINGLE_FLAG)) {
logonInfos = handleSingleManage(olduri);
}
if (logonInfos == null) {
PostMethod postMethod = setPostRequestInfos(logonSite);
String newuri = path + Constants.ERROR_PAGE;
try {
httpClient.executeMethod(postMethod);
logonInfos = getLocation(postMethod, path);
} catch (Exception e) {
logonInfos = new HashMap<String, Object>();
logonInfos.put(loginInfs.getUrl(), newuri);
log.error("network errors or device service stop.");
} finally {
postMethod.releaseConnection();
}
}
return logonInfos;
}
/**
* 处理单机登录,避免重复登录.
*
* @param olduri
* @return
*/
private Map<String, Object> handleSingleManage(String olduri) {
Map<String, Object> logonInfos = null;
int statecode = HttpStatus.SC_BAD_REQUEST;
if ((olduri != null) && (olduri.indexOf(loginInfs.getIpAddr()) != -1)) {
GetMethod getmethod = new GetMethod(olduri);
getmethod.setDoAuthentication(true);
try {
httpClient.executeMethod(getmethod);
// 因为getmethod.getResponseBodyAsString()有bug. 故采用此方法.
InputStream input = getmethod.getResponseBodyAsStream();
if (input != null && input.available() > 0) {
byte[] b = FileCopyUtils.copyToByteArray(input);
String datas = new String(b);
if (datas != null && datas.length() > 0
&& datas.indexOf(Constants.FRAME_SET) != -1)
statecode = HttpStatus.SC_OK;
}
} catch (HttpException e) {
log.error("network errors or device service stop.");
} catch (IOException e) {
log.error("network errors or device service stop.");
} finally {
getmethod.releaseConnection();
}
}
if (statecode == HttpStatus.SC_OK) {
logonInfos = new HashMap<String, Object>();
logonInfos.put(Constants.STATECODE, HttpStatus.SC_OK);
logonInfos.put(loginInfs.getUrl(), olduri);
}
return logonInfos;
}
/**
* 设置登录信息.
*
* @param logonSite
* @return
*/
private PostMethod setPostRequestInfos(String logonSite) {
PostMethod postMethod = new PostMethod(logonSite);
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(1, true));
String username = loginInfs.getUserName();
String pwd = loginInfs.getPassword();
NameValuePair userid = new NameValuePair(
loginInfs.getUser_name_param(), username);
NameValuePair password = new NameValuePair(loginInfs
.getUser_pwd_param(), pwd);
NameValuePair[] all = null;
if (Constants.MANAGER_FLAG.equals(loginInfs.getFlag())) {
all = new NameValuePair[] { userid, password,
new NameValuePair("mngip", "127.0.0.1"),
new NameValuePair("mngport", "" + Constants.PHPCOMM_PORT) };
} else {
all = new NameValuePair[] { userid, password };
}
postMethod.setRequestBody(all);
return postMethod;
}
private Map<String, Object> getLocation(PostMethod post, String path) {
Map<String, Object> backInfos = new HashMap<String, Object>();
String newuri = path + Constants.ERROR_PAGE;
int statuscode = post.getStatusCode();
if (isSuccess(statuscode)) {
newuri = getLocation(post);
Cookie[] logoncookies = httpClient.getState().getCookies();
Map<String, String> cookieInfos = getCookiesInfos(logoncookies);
newuri = newuri + "?" + SESSION_ID + "="
+ cookieInfos.get(SESSION_ID);
backInfos.put(SESSION_ID, cookieInfos.get(SESSION_ID));
if (loginInfs.getUrl().equals(Constants.MANAGER_OLD_URL)) {
newuri += Constants.MOCKDEV;
}
int bindex = newuri.indexOf(loginInfs.getIpAddr())
+ loginInfs.getIpAddr().length();
String firpart = newuri.substring(0, bindex);
String secpart = newuri.substring(bindex);
newuri = firpart + ":" + loginInfs.getPort() + secpart;
backInfos.put(loginInfs.getUrl(), newuri);
backInfos.put(Constants.STATECODE, HttpStatus.SC_OK);
}
return backInfos;
}
/**
* 检测返回的状态码.
*
* @param statusCode
* @return
*/
private boolean isSuccess(int statusCode) {
boolean isSuccess = false;
int[] codes = { HttpStatus.SC_MOVED_TEMPORARILY,
HttpStatus.SC_MOVED_PERMANENTLY, HttpStatus.SC_SEE_OTHER,
HttpStatus.SC_TEMPORARY_REDIRECT };
for (int index = 0; index < codes.length; index++) {
if (statusCode == codes[index]) {
isSuccess = true;
break;
}
}
return isSuccess;
}
/**
* 过滤cookie, 取得SESSION_ID所在cookie的信息.
*
* @param logoncookies
* Cookie[]
* @return cookie Map<String, String>
*/
private Map<String, String> getCookiesInfos(Cookie[] logoncookies) {
Map<String, String> cookie = new HashMap<String, String>();
for (int index = 0; index < logoncookies.length; index++) {
String name = logoncookies[index].getName();
if (name.equalsIgnoreCase(SESSION_ID)) {
cookie.put(SESSION_ID, logoncookies[index].getValue().trim());
break;
}
}
return cookie;
}
/**
* 取得uri.
*
* @param post
* @return
*/
private String getLocation(PostMethod post) {
String uri = null;
Header redirect = post.getResponseHeader(LOCATION);
if (redirect != null) {
uri = redirect.getValue();
if (StringUtil.isEmpty(uri))
uri = "/";
}
return uri;
}
}
发表评论
-
toString 方法
2014-11-06 14:28 346@Override public String to ... -
Java 反射研究Demo
2013-10-16 14:27 982需要JDom.jar package test; ... -
[转]Android开发者必须深入学习的10个应用开源项目
2010-10-15 15:33 664http://hailinhe1986-163-com.ite ... -
Android Intent的几种用法全面总结
2010-10-15 15:31 699http://vvsongsunny.iteye.com/bl ... -
Android读取txt的方法
2010-10-15 15:26 14931、放入到资源文件夹里面,也就是所创建android工程的re ... -
Android中Intent的用法总结
2010-10-14 22:35 0http://jobenc.iteye.com/blog/71 ... -
android
2010-10-14 14:48 0虽然Smack在PC上可以工作得很好,功能也很强大,但在OPh ... -
android
2010-10-08 11:09 0http://androidappdocs-staging.a ... -
mysql group_concat用法
2010-09-30 13:46 974http://blog.sina.com.cn/s/blog_ ... -
Httpclient 下载资源
2010-07-30 13:28 1183HttpClient 下载网络资源 所需commons-ht ... -
Javascript 基本操作
2010-04-17 10:44 7011:Div的隐藏与显示 <script type=&q ... -
判断形如((()))的字符串格式是否正确
2010-04-13 19:35 725对于判断字符串格式的这一类问题,解决办法由很多,最先想到得方法 ... -
MyEclipse继承属性编辑器
2010-03-18 19:35 1323在MyEclipse下添加属性编辑器: 在Eclipse的He ... -
判断是否为素数
2010-03-14 09:07 1060判断一个数是否为素数,方法很简单,实现如下: /* ... -
Byte,Short,Integer以及Long对象在不同数值范围内的比较情况总结
2010-03-14 08:50 3677在Java语言中,整型对象在不同数值范围内的比较分两种情况: ...
相关推荐
同时,注意设置合理的连接超时、读取超时等参数,以应对网络延迟或服务器响应慢的情况。 至于"Grabticket"这个场景,可能是模拟抢票应用,这时可能需要在短时间内发送大量POST请求到服务器,以尝试获取稀缺资源。在...
可以通过设置连接超时、读写超时、最大连接数、连接复用策略等来优化HttpClient的性能。 10. **异步操作**: HttpClient也支持异步操作,通过`HttpAsyncClient`类,可以在回调函数中处理响应,适合于高并发场景。...
这个压缩包“Java获取MQ连接数的Demo.zip”提供了一个简单的Java示例,用于展示如何通过编程方式获取RabbitMQ服务器的连接数。以下是对这个Demo的详细解释: 首先,为了与RabbitMQ交互,我们需要引入RabbitMQ的Java...
- 对于高并发场景,应适当调整连接池参数,如最大连接数、超时时间等。 HttpClient 4.5.5 作为一个成熟的 HTTP 客户端库,不仅提供了丰富的功能,还具有良好的可扩展性和灵活性。开发者可以根据具体需求对其进行...
通过配置最大连接数、每个路由的最大连接数以及连接超时等参数,可以有效控制资源使用。 4. **异步编程支持** HttpClient 4.5提供了`AsyncHttpClient`类,支持异步操作。异步请求返回`Future<HttpResponse>`对象,...
连接管理器可以设置超时、重试策略、最大连接数等参数。 3. **身份验证**:HttpClient支持多种身份验证机制,包括基本认证、摘要认证、NTLM、Kerberos等,能够处理跨域和多层代理的认证问题。 4. **Cookie管理**:...
// 将每路由最大连接数设为20 CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .build(); ``` **2.3 通过API配置超时** 在HttpClient 4.3及更高版本中,可以使用更高级的API...
- **连接参数**: 连接参数用于控制连接的行为,如最大连接数、连接超时时间等。 **2.2 持久连接** - **持久连接**: HTTP/1.1默认使用持久连接,这意味着在一个TCP连接上可以发送多个请求。 **2.3 HTTP连接路由** ...
// 每个路由的最大连接数 CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build(); ``` 6. **重试策略** HttpClient还提供了重试机制,当请求失败时自动重试...
- 连接池:使用`PoolingHttpClientConnectionManager`管理HTTP连接,可设置最大连接数、超时时间等。 - 请求路由:通过`HttpRequestExecutor`和`HttpClientConnectionManager`处理请求路由和重试策略。 4. **请求...
它还支持连接池,允许开发者配置最大连接数、超时时间等参数,以优化资源使用。 3. **异步处理**:除了传统的同步请求模式,HttpClient还提供了异步请求模式,使得在网络通信中可以实现非阻塞操作,提升应用的响应...
1. **基于 HttpCore**:HttpClient 是基于 HttpCore 实现的客户端 HTTP 传输类库,这意味着它能够处理 HTTP 协议的基本层面,包括连接管理、请求序列化和响应解析等。 2. **传统 IO 模型**:它基于传统的阻塞式 I/...
4. 性能优化:根据实际需求调整HttpClient的配置参数,如连接超时时间、最大连接数等。 总的来说,HTTPClient和HTTPCore是Java进行HTTP通信的重要工具,它们提供了强大的功能和灵活性,使得开发者能够方便地与远程...
2. **正确配置连接池**:合理设置连接池的最大连接数和超时时间,防止资源耗尽或长时间等待。 3. **异常处理**:对可能抛出的网络异常进行妥善处理,确保程序的健壮性。 4. **性能优化**:根据实际需求选择同步或...
- **连接池管理**:长期运行的服务应使用连接池,避免过多的连接创建和销毁,同时要注意设置合理的最大连接数和超时时间。 - **性能优化**:根据需求调整并发数,合理设置读写超时,避免阻塞。 - **安全性**:处理...
这可以通过`PoolingHttpClientConnectionManager`类实现,可以设置最大连接数、超时时间等参数。 2. **请求和响应处理**:HTTPClient支持GET、POST以及其他HTTP方法,同时可以处理HTTP头、Cookie、身份验证等。`...
2. **连接管理**:HttpClient 提供了`HttpConnectionManager`接口,用于管理与服务器的持久连接,优化性能,如复用连接、控制最大并发连接数等。`SingleClientConnManager`和`MultiThreadedHttpConnectionManager`是...
四、使用HttpClient-4.2.5.jar的注意事项 1. 性能优化:虽然HttpClient功能强大,但在现代Android环境中,可能不如Volley或OkHttp高效。因此,考虑性能和维护成本时,建议逐步迁移至更现代的库。 2. 兼容性问题:...
你可以通过`setMaxTotalConnections`和`setDefaultMaxPerRoute`来限制连接池的最大连接数。 然而,需要注意的是,尽管Apache Commons HttpClient在过去是常用的HTTP客户端库,但它现在已经被官方弃用,推荐使用Java...