Java访问网络,模拟登陆,进入网站内部(使用HttpClient)

Java访问网络,模拟登陆,进入网站内部(使用HttpClient), jar包在下面可以直接下载

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class Link {
static final String LOGON_SITE = “localhost” ;//主机地址
static final int LOGON_PORT = 18181;//端口号
public static void main(String[] args) throws Exception{
HttpClient client = new HttpClient();//打开新窗口
client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);//配置
// 模拟手动登录页面,home是处理登陆的antion
PostMethod post = new PostMethod( “/home” );
NameValuePair username = new NameValuePair( “username” , “admin” );
NameValuePair pass = new NameValuePair( “password” , “admin” );
post.setRequestBody( new NameValuePair[]{username,pass});
int status = client.executeMethod(post);
post.releaseConnection();
// 查看 cookie,并传递Cookies到服务器认证
CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, “/” , false , client.getState().getCookies());
if (cookies.length == 0) {
System.out.println( “没有Cookies” );
} else {
for ( int i = 0; i < cookies.length; i++) {
System.out.println(“Cookies:”+cookies[i].toString());
}
}
// 因为前面已经登陆了,也加入了Cookies,所以才可以直接访问这个地址,这个才是需要访问的真正antion
GetMethod get=new GetMethod(“/corpcode/renzheng?Corpcode=C10147&Code=1231”);
client.executeMethod(get);
System.out.println(“Get请求:”+get.getResponseBodyAsString());
get.releaseConnection();
}
}

 

jar包下载 lib

本站的文章多是老王开发工作中问题的记录,一个字一个字敲的,切实可行,可以分享,需要留个原文链接,至少也意思意思吧!
vsalw技术博客 » Java访问网络,模拟登陆,进入网站内部(使用HttpClient)

你想下载这个主题吗?

沟通一下 扯会蛋