www.x158.cn这是一个信息发布网站,他的登陆页面是在www.x158.cn/bg/login.asp
以下是利用httpclient做的一个自动登陆程序。
package test;
import java.io.IOException;
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;
public class PostForm {
public static void main(String[] args) throws HttpException, IOException {
UserPwd userpwd = new UserPwd("ucanhealth", "1234567");
Zh zh = new Zh();
System.out.println(zh.iso2utf(userpwd.getInfo())); // 打印返回结果
}
}
class UserPwd {
String user, pwd;
public UserPwd(String user, String pwd) // 构造函数
{
this.user = user;
this.pwd = pwd;
}
public String getInfo() {
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost("www.x158.cn", 80, "http"); // url的地址,端口,协议
PostMethod post = new PostMethod("/bg/login.asp"); // 执行查询的网页
post.addParameter(new NameValuePair("username", user));// 传递文本框的name及values
post.addParameter("password", pwd);// 传递文本框的pwd及values
String s = null;
try {
int i = client.executeMethod(post);
System.out.println("record statuscode:" + i);
s = post.getResponseBodyAsString();
///
//检查是否重定向
int statuscode = post.getStatusCode();
if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||
(statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||
(statuscode == HttpStatus.SC_SEE_OTHER) ||
(statuscode == HttpStatus.SC_TEMPORARY_REDIRECT))
{
// 读取新的URL地址
Header header = post.getResponseHeader("location");
if (header != null) {
String newurl = header.getValue();
if ((newurl == null) || (newurl.equals("")))
newurl = "/";
GetMethod redirect = new GetMethod(newurl);
client.executeMethod(redirect);
System.out.println("Redirect:"+ redirect.getStatusLine().toString());
redirect.releaseConnection();
} else
System.out.println("Invalid redirect");
}
//
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
class GetInfo {
private String url;
GetInfo(String url) {
this.url = url;
}
void getInfo() throws IOException {
String html = null;
HttpClient hc = new HttpClient();
// create get method instance
GetMethod gm = new GetMethod(url);
// 使用系统提供的默认的恢复策略
gm.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
try {
int statuscode = hc.executeMethod(gm);
if (statuscode != HttpStatus.SC_OK) {
System.err.print("method failed:" + gm.getStatusLine());
}
byte[] responseBody = gm.getResponseBody();
html = new String(responseBody);
} catch (HttpException e) {
System.out.println("Please check your provided http address!");
e.printStackTrace();
}
System.out.println(html);
}
}
}
自动登陆程序事例
最新推荐文章于 2023-01-10 04:11:16 发布