java 模拟登录 httpclient_java web中 HttpClient模拟浏览器登录后发起请求

httpclient模拟浏览器登录后发起请求

浏览器实现这个效果需要如下几个步骤:

1请求一个需要登录的页面或资源

2服务器判断当前的会话是否包含已登录信息。如果没有登录重定向到登录页面

3手工在登录页面录入正确的账户信息并提交

4服务器判断登录信息是否正确,如果正确则将登录成功信息保存到session中

5登录成功后服务器端给浏览器返回会话的sessionid信息保存到客户端的cookie中

6浏览器自动跳转到之前的请求地址并携带之前的cookie(包含登录成功的sessionid)

7服务器端判断session中是否有成功登录信息,如果有则将请求的资源反馈给浏览器

package com.artsoft.demo;

import java.io.fileoutputstream;

import org.apache.http.httpentity;

import org.apache.http.httpresponse;

import org.apache.http.client.cookiestore;

import org.apache.http.client.methods.httpget;

import org.apache.http.client.methods.httppost;

import org.apache.http.impl.client.defaulthttpclient;

import org.apache.http.impl.conn.poolingclientconnectionmanager;

import org.apache.http.util.entityutils;

/**

* todo(用一句话描述该文件的作用)

*

* @title: httpclientdemo.java

* @author zhangjinshan-ghq

* @date 2014-6-11 14:59:04

*/

public class httpclientdemo

{

/**

* the main method.

*

* @param args the arguments

* @throws exception the exception

*/

public static void main(string[] args) throws exception

{

getresoucesbylogincookies();

}

/**

* 根据登录cookie获取资源

* 一切异常均未处理,需要酌情检查异常

*

* @throws exception

*/

private static void getresoucesbylogincookies() throws exception

{

httpclientdemo demo = new httpclientdemo();

string username = "......";// 登录用户

string password = "......";// 登录密码

// 需要提交登录的信息

string urllogin = "http://hx.buscoming.cn/api/security/logon?usercode=" + username + "&password=" + password;

// 登录成功后想要访问的页面 可以是下载资源 需要替换成自己的iteye blog地址

string urlafter = "http://hx.buscoming.cn/api/security/getloginaccount";

defaulthttpclient client = new defaulthttpclient(new poolingclientconnectionmanager());

/**

* 第一次请求登录页面 获得cookie

* 相当于在登录页面点击登录,此处在url中 构造参数,

* 如果参数列表相当多的话可以使用httpclient的方式构造参数

* 此处不赘述

*/

httppost post = new httppost(urllogin);

httpresponse response = client.execute(post);

httpentity entity = response.getentity();

cookiestore cookiestore = client.getcookiestore();

client.setcookiestore(cookiestore);

/**

* 带着登录过的cookie请求下一个页面,可以是需要登录才能下载的url

* 此处使用的是iteye的博客首页,如果登录成功,那么首页会显示【欢迎xxxx】

*

*/

httpget get = new httpget(urlafter);

response = client.execute(get);

entity = response.getentity();

/**

* 将请求结果放到文件系统中保存为 myindex.html,便于使用浏览器在本地打开 查看结果

*/

string pathname = "d:\\index.html";

writehtmltofile(entity, pathname);

}

/**

* write html to file.

* 将请求结果以二进制形式放到文件系统中保存为.html文件,便于使用浏览器在本地打开 查看结果

*

* @param entity the entity

* @param pathname the path name

* @throws exception the exception

*/

public static void writehtmltofile(httpentity entity, string pathname) throws exception

{

byte[] bytes = new byte[(int) entity.getcontentlength()];

fileoutputstream fos = new fileoutputstream(pathname);

bytes = entityutils.tobytearray(entity);

fos.write(bytes);

fos.flush();

fos.close();

}

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

希望与广大网友互动??

点此进行留言吧!


版权声明:本文为weixin_34430692原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。