HttpClient4.5实现登陆和跳转

package com.demo;

import org.apache.http.HeaderIterator;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.util.EntityUtils;

/**
* httpclient模拟登陆并跳转
*
* @author steffen
*
*/
public class Login {
public static void main(String[] args) {
try {
// 先访问首页,得到cookie
// cookie信息自动保存在HttpClient中
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(new BasicCookieStore())
.setRedirectStrategy(new LaxRedirectStrategy()).build();
//登陆智慧城市
HttpPost postMethod = new HttpPost(“http://localhost:8080/manager/login“);

        httpClient.execute(postMethod);
        // 携带cookie访问登录网面
        // 设置登录的账号与密码
        HttpUriRequest login = RequestBuilder.post().setUri("http://localhost:8080/manager/login")
                .addParameter("username", "beijingyidu").addParameter("password", "123456").build();
        // httpclient访问登录网页,并得到响应对象
        CloseableHttpResponse response = httpClient.execute(login);
        // 响应文本
        String content = EntityUtils.toString(response.getEntity());
        EntityUtils.consume(response.getEntity());
        // 输出响应页面源代码
        System.out.println(content);
        // 输出为302,也就是说网页发生了重定向
        // 得到重定向后的
        HeaderIterator redirect = response.headerIterator("location");
        while (redirect.hasNext()) {
            // 使用get请求,访问登陆后的页面
            HttpGet getMethod = new HttpGet(redirect.next().toString());
            CloseableHttpResponse response2 = httpClient.execute(getMethod);
            // 得到返回文本
            String content1 = EntityUtils.toString(response.getEntity());
            EntityUtils.consume(response.getEntity());
            // 打印请求文本
            System.out.println("响应请求文本是:" + content1);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

}

转载于:https://www.cnblogs.com/gent95/p/8325564.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值