注意设置httpclient连接数

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;
}

}

你可能感兴趣的:(apache,Web,.net,Blog)