The concrete implementation of httpclient simulated login of USES js to set cookies

  • 2020-03-30 00:49:09
  • OfStack

Httpclient mock login (using js to set cookie)
 
<html> 
<meta http-equiv='Content-Type' content='text/html; charset=gb2312'> 
<link rel=stylesheet type=text/css href='/bbs.css'> 
<script>document.cookie='utmpnum=51;path=/;domain=.' + window.location.host</script> 
<script>document.cookie='utmpkey=20154732;path=/;domain=.' + window.location.host</script> 
<script>document.cookie='utmpuserid=yay;path=/;domain=.' + window.location.host</script> 
<meta http-equiv='Refresh' content='0; url=/firstpage.php'> 

H4ttpclient 4.3:

The simplest method is to customize an httpclient through the obtained cookie. According to the above example, the method is as follows:
 
CookieStore cookieStore = new BasicCookieStore(); 

for (int i = 0; i < 3; i++) { 
String name; 
String value; 
int flag=s.indexOf("document.cookie"); 
s=s.substring(flag+17); 
flag=s.indexOf('='); 
name=s.substring(0, flag); 
value=s.substring(flag+1, s.indexOf(';')); 
BasicClientCookie cookie = new BasicClientCookie(name, 
value); 
cookie.setVersion(0); 
cookie.setDomain(".www.zju88.org"); //This url corresponds to <Span style="font-family: Arial, Helvetica, sans-serif;> Return value of window.location.host </ span>
cookie.setPath("/"); 
cookieStore.addCookie(cookie); 
} 
// Set the store 
CloseableHttpClient httpclient = HttpClients.custom() 
.setDefaultCookieStore(cookieStore) 
.build(); 

Android:

I searched for a long time but could not find the API corresponding to the above method, so I had to add cookie before each access
 
String cookie=""; 
for (int i = 0; i < 3; i++) { 
String name; 
String value; 
int flag=s.indexOf("document.cookie"); 
s=s.substring(flag+17); 
flag=s.indexOf('='); 
name=s.substring(0, flag); 
value=s.substring(flag+1, s.indexOf(';')); 
cookie +=name +"="+value; 
if(i!=2) 
cookie+=";"; 
} 

 
HttpGet httpget = new HttpGet(url); 
httpget.addHeader("Cookie",cookie); 
//If there is already a cookie in httpclient, it may be necessary to set the cookie policy of httpclient. For details, please refer to the official API (:
HttpResponse response = httpclient.execute(httpget); 

Ps: if you are using Java SE, you can also use the htmlunit class, which executes js.

Related articles: