Using Okhttp to simulate landing leetcode

Source: Internet
Author: User

Objective

There are many tutorials on the web that simulate landing leetcode, but they are basically implemented using Python. As a Java language enthusiast, so want to use Java to implement the next. In the realization of the process, also encountered some pit points, so as a record.

Process

Analyze landing page based on browser F12

As can be seen, leetcode generate a token, and then in the landing time with this information, so we simulate the general idea of landing: first get a cookie (including token), and then on the landing time with this cookie information, complete Leetcode Verification mechanism to perform a mock landing.
However, the direct simulation with login (username), password (password), Csrfmiddlewaretoken (authentication information) is unsuccessful, prompting Forbidden. Thinking without fruit, another way to open up ideas.
Use Fiddler to grab the packet, not logged in, data such as (can also be used to analyze the browser F12):

Login status, data such as, we can find that its content-type field is not the same as our usual values, it is the multipart/form-data format, so we are in the simulation landing, we want to consider it in.

Create a Multipart/form-data media format, and then generate the request body we want, as to what kind of request we want, the format of which can be learned from the results of the Fiddler grab packet.
Specific details in the Syntaxview are as follows:

It is noteworthy that the boundary in Content-type has only four "-", and there are six "-" in the request body, which has been denied access because of ignoring this.

public static final String boundary = "----WebKitFormBoundaryhG2vKxp7y2GAwhPX";public static final MediaType MULTIPART = MediaType.parse("multipart/form-data; boundary=" + boundary);String form_data = "--" + boundary + "\r\n"                + "Content-Disposition: form-data; name=\"login\"" + "\r\n\r\n"                + usrname + "\r\n"                + "--" + boundary + "\r\n"                + "Content-Disposition: form-data; name=\"password\"" + "\r\n\r\n"                + passwd                + "--" + boundary + "\r\n"                + "Content-Disposition: form-data; name=\"csrfmiddlewaretoken\"" + "\r\n\r\n"                + csrftoken + "\r\n"                + "--" + boundary + "--";        RequestBody requestBody = RequestBody.create(MULTIPART,form_data);
Results

The returned message is printed, and the following information indicates that the simulation has been successful.

This can also be confirmed from the Fiddler's clutch results.

Code
Package Leetcodelogin;import Okhttp3.*;import Org.jsoup.connection;import org.jsoup.jsoup;import Java.io.ioexception;import java.util.*;import static Java.lang.system.out;public class Login {public static final Stri    ng boundary = "----WEBKITFORMBOUNDARYHG2VKXP7Y2GAWHPX"; public static final MediaType MULTIPART = Mediatype.parse ("Multipart/form-data;    boundary= "+ boundary);        public static void Main (String ... args) throws IOException {Scanner Scanner = new Scanner (system.in);        String url = "https://leetcode.com/accounts/login/";        String usrname = "xxx";        String passwd = "xxx"; Connection.response response1 = jsoup.connect (URL). Method (Connection.Method.GET). Execute ()        ;        String Csrftoken = Response1.cookie ("Csrftoken");        String __cfduid = Response1.cookie ("__cfduid");        Out.println ("Csrftoken =" + Csrftoken);        Out.println ("__cfduid =" + __cfduid); Okhttpclient client = new Okhttpclient (). Newbuilder (). Followredirects (False). Followsslredirects (False). build (); String Form_data = "--" + boundary + "\ r \ n" + "content-disposition:form-data; Name=\ "login\" "+" \r\n\r\n "+ Usrname +" \ r \ n "+"--"+ boundary +" \ r \ n "+ "Content-disposition:form-data; Name=\ "password\" "+" \r\n\r\n "+ passwd +"--"+ boundary +" \ r \ n "+" Conten T-disposition:form-data;        Name=\ "csrfmiddlewaretoken\" "+" \r\n\r\n "+ Csrftoken +" \ r \ n "+"--"+ Boundary +"--";        Requestbody requestbody = requestbody.create (Multipart,form_data); Request Request = new Request.builder (). AddHeader ("Content-type", "multipart/form-data;                boundary= "+ boundary). AddHeader (" Connection "," keep-alive "). AddHeader (" Accept "," */* ") . AddHeader ("Origin", "Https://leetcode. com "). AddHeader (" Referer ", url). AddHeader (" Cookie "," __cfduid= "+ __cfduid +"; "+" Csrftok        en= "+ Csrftoken). Post (requestbody). URL (URL). build ();        Response Response = client.newcall (Request). Execute ();        Out.println (Response.message ());        Out.println (Response.headers ());    Out.println (Response.body (). String ()); }}

It is important to note that in the code above, we disable redirection by using the following code, to handle the redirect request ourselves, and refer to the use of okhttp for redirection interception processing, which would also cause the simulation to fail if no redirect interception was performed.

    .followRedirects(false)    .followSslRedirects(false)
Written in the last

The simulation landing, although the code is very simple, but it has experienced some twists and turns, than the Python and JS write the simulation of the code, with Java to do the simulation seems to be a few trivial details, for the specific why Python and JS so that the principles of the processing of the principle is still pondering. This time, also got the help of friend Faberry, in some places gave the opinion.

Using Okhttp to simulate landing leetcode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.