java htttp 登录返回cookie 通过cookie 访问其他资源

Posted yaoyao66123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java htttp 登录返回cookie 通过cookie 访问其他资源相关的知识,希望对你有一定的参考价值。


import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by yaoyao on 16/3/19.
 */
public class test0319 {


    int countUrl=0;


    public static void main(String[] args) {

        try {
//            String cookie = new test0319().login();
            new test0319().getOnehtml("http://192.168.1.103:8090/front/sku/list","utf-8","[rememberMe=deleteMe; Path=/front; Max-Age=0; Expires=Fri, 18-Mar-2016 16:15:23 GMT, JSESSIONID=68683D96F61B34C1CDFB5431ABA5B4BA; Path=/front/; HttpOnly]");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }




    public String getOneHtml(String htmlurl,String encoding,String cookie) throws IOException, InterruptedException
    {

        //最多重复请求5次,用来反爬的
        if(countUrl==5){
            countUrl=0;
            return "0";
        }
        //System.out.println(cookie);
        StringBuilder content = new StringBuilder();
        HttpURLConnection httpConn = null;
        try
        {
            URL url = new URL(htmlurl);

            httpConn = (HttpURLConnection) url.openConnection();
            //头设置,get方法

            HttpURLConnection.setFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.setRequestProperty("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36");
            httpConn.setRequestProperty("Connection","keep-alive");
            httpConn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml");
            httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            httpConn.setRequestProperty("cookie",cookie);
            httpConn.setRequestProperty("Cache-control","no-cache, no-store");
            httpConn.setRequestProperty("Host","http://192.168.1.103:8090");
            httpConn.setConnectTimeout(20000);
            httpConn.setReadTimeout(20000);
            // logger.info(httpConn.getResponseMessage());
            BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), encoding));////打开连接,获取内容
            String temp;
            while ((temp = in.readLine()) != null)
            //替换点一些无用到符号
            {
                content.append(temp);
            }
            in.close();
            httpConn.disconnect();

        }
        catch (final MalformedURLException me)
        {
            System.out.println("url不存在!");
            me.getMessage();
            throw me;
        }
        catch (final FileNotFoundException me)
        {
            System.out.println(htmlurl+"反爬启动");
            return "0";
        }
        catch (final IOException e)
        {
            e.printStackTrace();
            System.out.println("反爬启动:"+htmlurl+"次数:"+countUrl++);
            httpConn.disconnect();
            Thread.sleep(20000);
            return this.getOneHtml(htmlurl, encoding,cookie);
        }

        //System.out.println(sb);
        countUrl=0;
        httpConn.disconnect();

        System.out.println(content.toString());
        return content.toString();

    }

    public String login() throws MalformedURLException, InterruptedException {

        String htmlurl = "http://192.168.1.103:8090/front/login";
        HttpURLConnection httpConn = null;
        String cookie = "";
        try {
            URL url = new URL(htmlurl);

            httpConn = (HttpURLConnection) url.openConnection();

            HttpURLConnection.setFollowRedirects(true);
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36");
            httpConn.setRequestProperty("Connection", "keep-alive");
            httpConn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("Cache-control", "no-cache, no-store");
            httpConn.setRequestProperty("Host", "http://192.168.1.103:8090/front");
            //httpConn.setRequestProperty("Referer","https://www.linkedin.com/uas/login?session_redirect=http://www.linkedin.com/profile/view?id=222323610&authType=name&authToken=fcEe");
            //post方法,重定向设置
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setUseCaches(false);
            httpConn.setInstanceFollowRedirects(false);
            //写入,post方法必须用流写入的方式传输数据
            StringBuffer str_buf = new StringBuffer(4096);
            OutputStream os = httpConn.getOutputStream();
            str_buf.append("username").append("=").append("13062779665").append("&");
            str_buf.append("password").append("=").append("111111").append("&");
            //str_buf.append("session_redirect").append("=").append(redictURL);
            os.write(str_buf.toString().getBytes());
            os.flush();
            os.close();
            httpConn.setConnectTimeout(20000);
            httpConn.setReadTimeout(20000);
            //获取重定向和cookie
            //String redictURL= httpConn.getHeaderField( "Location" );
            //System.out.println("第一次请求重定向地址 location="+redictURL);

            //获取cookie
            Map<String, List<String>> map = httpConn.getHeaderFields();
            //System.out.println(map.toString());
            Set set = map.keySet();
            for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
                String key =  String.valueOf(iterator.next());
                if (key != null) {
                    if (key.equals("Set-Cookie")) {
                        System.out.println("key=" + key + ",开始获取cookie"+map.get("Set-Cookie").toString());
                        List<String> list = map.get(key);
                        for (String str : list) {
                            String temp = str.split("=")[0];
                            //System.out.println(temp);

                            //cookie包含到信息非常多,调试发现登录只需这条信息
//                            if (temp.equals("li_at")) {
                                cookie = str;
                                return cookie;
//                            }

                        }
                    }
                }

            }
            httpConn.disconnect();

        } catch (final MalformedURLException me) {
            System.out.println("url不存在!");
            me.getMessage();
            throw me;
        } catch (final FileNotFoundException me) {
            System.out.println(htmlurl + "反爬启动");
            return "0";
        } catch (final IOException e) {
            e.printStackTrace();
            System.out.println("反爬启动:" + htmlurl + "次数:" + countUrl++);
            httpConn.disconnect();
            Thread.sleep(20000);
            return login();
        }
        System.out.println(cookie);
        return cookie;
}}

以上是关于java htttp 登录返回cookie 通过cookie 访问其他资源的主要内容,如果未能解决你的问题,请参考以下文章

当我们通过 facebook 登录时如何删除 facebook cookie

Java通过httpclient获取cookie模拟登录

java爬虫利用Jsoup获取需要登陆的网站中的内容(无验证码的登录)

java如何用cookies保存用户登录信息

java如何用cookies保存用户登录信息

前端判断用户登录状态方法