采用httpclient 模拟cookie | 张恒镭的博客

采用httpclient 模拟cookie

时间:14-03-31 栏目:java 作者:longteng 评论:0 点击: 2,881 次

其实httpclient里能默认处理cookies

 

官网描述:

supports automatic management of cookies, including allowing the server to set cookies and automatically return them to the server when required. It is also possible to manually set cookies to be sent to the server.

下面是示例 如何手动设置cookies

package multi_downloader.swtui.httpclient;
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.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
public class TestHttpclientCookie {
    public static void main(String[] args){
        //登陆 Url
        String loginUrl = "http://192.168.6.31:4663/transfer/login";
        //需登陆后访问的 Url
        String dataUrl = "http://192.168.6.31:4663/transfer/user";
        HttpClient httpClient = new HttpClient();
        //模拟登陆,按实际服务器端要求选用 Post 或 Get 请求方式
        PostMethod postMethod = new PostMethod(loginUrl);
        //设置登陆时要求的信息,一般就用户名和密码,验证码自己处理了
        NameValuePair[] data = {
                new NameValuePair("username", "test"),
                new NameValuePair("password", "111111"),
                new NameValuePair("code", "anyany")
        };
        postMethod.setRequestBody(data);
        try {
            //设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            httpClient.executeMethod(postMethod);
            //获得登陆后的 Cookie
            Cookie[] cookies=httpClient.getState().getCookies();
            String tmpcookies= "";
            for(Cookie c:cookies){
                tmpcookies += c.toString()+";";
            }
            //进行登陆后的操作
            GetMethod getMethod = new GetMethod(dataUrl);
            //每次访问需授权的网址时需带上前面的 cookie 作为通行证
            getMethod.setRequestHeader("cookie",tmpcookies);
            //你还可以通过 PostMethod/GetMethod 设置更多的请求后数据
            //例如,referer 从哪里来的,UA 像搜索引擎都会表名自己是谁,无良搜索引擎除外
            postMethod.setRequestHeader("Referer", "http://unmi.cc");
            postMethod.setRequestHeader("User-Agent","Unmi Spot");
            httpClient.executeMethod(getMethod);
            //打印出返回数据,检验一下是否成功
            String text = getMethod.getResponseBodyAsString();
            System.out.println(text);
        } catch (Exception e) {
            e.printStackTrace();
        }  
    }
}

 

总结: client里获取cookies --- httpClient.getState().getCookies();

header里获取cookie ---- get.getRequestHeaders();//获取的header数组 里面有cookies 选项

声明: 本文由( longteng )原创编译,转载请保留链接: 采用httpclient 模拟cookie

采用httpclient 模拟cookie:等您坐沙发呢!

发表评论




------====== 本站公告 ======------
欢迎关注我的博客。

其他