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();
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM