Java模拟浏览器登录带保护的网站

Java模拟浏览器登录带保护的网站

刚学习Android的同学,像我一样,在了解了Android的基本布局,组件和其他基本知识后,就迫不及待的向编写一个自己的软件。对于在校的同学来说,写一个关于教务的app还是挺有价值的,不管是锻炼做项目的能力,还是学习其他相关知识,都是一个不错的选择。我们的教务系统一般都是可以在浏览器登录的,那么我们就可以通过编写程序来模拟浏览器这一登录过程。


GET登录网页,得到cookie

想要登录教务系统,首先需要获取到登录到系统的页面
一般在GET获取这个网址的时候会同时得到一个cookie,大概流程如下图:

访问流程
获取初始cookie

如何获取到这个cookie呢?看我接下来的代码:
public static String getcookies() throws IOException {
        CookieManager manager=new CookieManager();
        manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(manager);
        URL url=new URL(A_URL);
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
        conn.getHeaderFields();
        CookieStore store = manager.getCookieStore();
        String cookies = store.getCookies().toString();
        cookies = cookies.replace("[", "");
        cookies = cookies.replace("]", "");
        return cookies;
    }

其中A_URL是登录页面的url,用GET获取这个页面时,服务器返回的数据头中会包含cookie信息。现在这个cookie还是没有用的,还需要服务器端将这个cookie与你的用户名密码绑定,就需要知道教务系统的登录地址,例如:

登录地址

POST用户名密码,绑定cookie

看一下浏览器进行POST请求时提交的数据及浏览器的请求头

表单数据

请求头

然后自己来完成这个动作

public static String doPost(){
        B_URL=A_URL+"?"+"username="+"你的学号"+"&passwd="+"你的密码"+"&login=%B5%C7%A1%A1%C2%BC";
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        try{
        URL url = new URL(B_URL);


        HttpURLConnection conn = (HttpURLConnection) url.openConnection();


        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0");

        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");

        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");

        conn.setRequestProperty("Referer", " http://xky.guet.edu.cn/student/public/login.asp");

        conn.setRequestProperty("Cookie", getcookies());

        conn.setRequestProperty("Connection", "keep-alive");

        conn.setRequestProperty("Upgrade-Insecure-Requests", "1");

        conn.setDoOutput(true);
        conn.setDoInput(true);

        out = new PrintWriter(conn.getOutputStream());
        out.flush();

        in = new BufferedReader(new  InputStreamReader(conn.getInputStream()));
        String line;
        while((line = in.readLine())!=null){
            result +="\n"+line;
        }
        }catch(Exception e){  
            System.out.println("发送POST请求异常"+e);  
            e.printStackTrace();  
        }finally{  
            try{  
                if(out!=null){  
                    out.close();  
                }  
                if(in!=null){  
                    in.close();  
                }  
            }catch(IOException ex){  
                ex.printStackTrace();  
            }  
        } 
        return result;
    }
利用cookie获取信息

到现在你的cookie就可以用了,例如获取学分:

public static String getCredit(){
        B_URL=A_URL+"?"+"term=&courselevel=null&ljtype=on&kcfw=0&jstype=pjxfj&lwOrderBy=stid&lwPageSize=50&lwBtnquery=%B2%E9%D1%AF";
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        try{
        URL url = new URL(B_URL);


        HttpURLConnection conn = (HttpURLConnection) url.openConnection();


        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0");

        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");

        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");

        conn.setRequestProperty("Referer", " http://xky.guet.edu.cn/student/public/login.asp");

        conn.setRequestProperty("Cookie", getcookies());

        conn.setRequestProperty("Connection", "keep-alive");

        conn.setRequestProperty("Upgrade-Insecure-Requests", "1");

        conn.setDoOutput(true);
        conn.setDoInput(true);

        out = new PrintWriter(conn.getOutputStream());
        out.flush();

        in = new BufferedReader(new  InputStreamReader(conn.getInputStream()));
        String line;
        while((line = in.readLine())!=null){
            result +="\n"+line;
        }
        }catch(Exception e){  
            System.out.println("发送POST请求异常"+e);  
            e.printStackTrace();  
        }finally{  
            try{  
                if(out!=null){  
                    out.close();  
                }  
                if(in!=null){  
                    in.close();  
                }  
            }catch(IOException ex){  
                ex.printStackTrace();  
            }  
        } 
        return result;
    }

好了,到现在模仿登录教务系统的java代码就完成了,剩下的就是将代码移植到Android应用中,编写界面,一个自己的Android app就可以完成了。

本人新手,有错指正,文章原创
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java中的HttpURLConnection类来模拟浏览器访问百度搜索。以下是一个简单的示例代码: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class BaiduSearch { public static void main(String[] args) { try { // 搜索关键词 String keyword = "java"; // 编码关键词 String encodedKeyword = URLEncoder.encode(keyword, "UTF-8"); // 百度搜索地址 String baiduSearchUrl = "https://www.baidu.com/s?wd=" + encodedKeyword; // 创建URL对象 URL url = new URL(baiduSearchUrl); // 创建HttpURLConnection对象 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法 connection.setRequestMethod("GET"); // 设置请求头信息,模拟浏览器访问 connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"); // 获取响应状态码 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 获取响应数据 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 输出响应数据 System.out.println(response.toString()); } else { System.out.println("请求失败,响应状态码为:" + responseCode); } } catch (Exception e) { System.out.println("请求失败,出现异常:" + e.getMessage()); } } } ``` 运行该代码后,控制台会输出百度搜索结果的HTML代码。注意,这里只是一个简单的示例,实际应用中还需要处理一些异常情况,如网络异常、响应状态码非200等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值