zoukankan      html  css  js  c++  java
  • java实现模拟登陆

    有时候我们在爬虫的时候,需要登陆,登陆后才可以获取相关信息,因此我们需要在一开始就实现一个模拟登陆的功能

    简单写了一下,还是很简单的

    import okhttp3.*;
    
    import java.io.IOException;
    
    
    public class Test {
    
    
        public static void main(String[] args) {
            String url = "https://***.com/login";
            String username = "username";
            String password = "password";
            Headers.Builder builder = new Headers.Builder();
            builder.add("Content-Type", "application/x-www-form-urlencoded");
            Headers headers = builder.build();
            RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("loginName", username)
                    .addFormDataPart("loginPwd", password)
                    .build();
            Response response = postData(url, headers, body);
            System.out.println(response.code());
            //拿到cookie
            String header = response.header("Set-Cookie");
            System.out.println(header);
    
    
    
        }
    
        public static Response postData(String url, Headers headers, RequestBody body) {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
    
            Request request = new Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .headers(headers)
                    .build();
            Response response = null;
            try {
                response = client.newCall(request).execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }
    
    }

     二、从request中获取cookie

    Headers initHeader(HttpServletRequest request) {
            Cookie[] cookies = request.getCookies();
            String cookieName = "SESSION";
            String cookieVal="";
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    cookieVal = cookie.getValue();
                }
            }
            Headers.Builder builder = new Headers.Builder();
            builder.add("Cookie", cookieName+"="+cookieVal);
            return builder.build();
        }
  • 相关阅读:
    I Hate It
    满减优惠[Offer收割]编程练习赛4
    积水的城市 hiho[Offer收割]编程练习赛4
    Subsequence 尺取法
    526. 优美的排列
    401. 二进制手表
    306. 累加数
    216. 组合总和 III
    131. 分割回文串
    ubuntu deepin-软件 分辨率的问题
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/15042877.html
Copyright © 2011-2022 走看看