Java 模拟cookie登陆

       最近在做将禅道上的功能接口做到手机端,在做登陆的时候,看了禅道的源码,是由cookie来登陆,所以要做一个模拟cookie登陆的接口,将拿到的cookie放到每次接口请求的头部中去,就可以正常访问了。

     

import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author: jljiang
 * @Description:Java 模拟cookie登陆
 * @Date: Created in  2019/1/16 15:14
 */
public class ImitateLoginController {

    public static void main(String args[]) throws Exception {
        //登陆接口地址
        String loginStr = "http://zenta.51fb.com/index.php?m=user&f=login";
        /**
         * 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如: // Using
         * java.net.URL and //java.net.URLConnection
         */
        URL url = new URL(loginStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection
                .getOutputStream(), "GBK");
        //其中的account和password可以通过控制台去查看,或者看页面html去查看
        out.write("account=you-user-name&password=you-password"); 
// remember to clean up
        out.flush();
        out.close();

// 取得cookie,使用该cookie放在头部就可以访问其他需要登陆才可以访问的接口了
        String cookieVal = connection.getHeaderField("Set-Cookie");

/*------------------------------------访问其他接口-------------------------------------------------*/
        String otherUrl = "http://zenta.51fb.com/index.php?m=bug&f=browse";
        url = new URL(otherUrl);
        HttpURLConnection otherConnection = (HttpURLConnection) url.openConnection();
        if(cookieVal != null){
            otherConnection.setRequestProperty("Cookie",cookieVal);
        }
        otherConnection.connect();
        InputStream urlStream = otherConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(urlStream));
        String content = null;
        StringBuilder total = new StringBuilder();
        while ((content = bufferedReader.readLine()) != null) {
            total.append(content);
        }
        bufferedReader.close();
        System.out.println(content);
    }
}

      

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值