Java – httpclient authentication, keep login status
So my goal is to log in to the forum using HTTP client, and then post a reply post on the forum My login is good, but when I post on the post, it says I'm not logged in Any ideas? I've tried to build HTTP client using cookies, but after I signed in, I looked at them and didn't have anything So I tried to make two calls using the same HTTP client, but it still didn't work
String username,password,threadNum,bumpMessage,bumpTimer; HttpClient http; public void login() throws ClientProtocolException,IOException,NoSuchAlgorithmException { this.http = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://www.sythe.org/login.PHP?do=login"); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("do","login")); params.add(new BasicNameValuePair("url","")); params.add(new BasicNameValuePair("vb_login_md5password",this.password)); params.add(new BasicNameValuePair("vb_login_md5password_utf",this.password)); params.add(new BasicNameValuePair("s","")); params.add(new BasicNameValuePair("vb_login_username",this.username)); params.add(new BasicNameValuePair("vb_login_password","")); httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); //Execute and get the response. HttpResponse response = http.execute(httppost); httpentity entity = response.getEntity(); } public void bump() throws ClientProtocolException,IOException { HttpPost httppost = new HttpPost("http://www.sythe.org/newreply.PHP?do=postreply&t=" + this.threadNum); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("title","")); params.add(new BasicNameValuePair("message",this.bumpMessage)); params.add(new BasicNameValuePair("wysiwyg","0")); params.add(new BasicNameValuePair("iconid","0")); params.add(new BasicNameValuePair("s","")); params.add(new BasicNameValuePair("posthash","")); params.add(new BasicNameValuePair("poststarttime","")); params.add(new BasicNameValuePair("loggedinuser","")); params.add(new BasicNameValuePair("multiquoteempty","")); params.add(new BasicNameValuePair("sbutton","Submit Reply")); params.add(new BasicNameValuePair("signature","1")); params.add(new BasicNameValuePair("parseurl","1")); params.add(new BasicNameValuePair("emailupdate","9999")); httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); //Execute and get the response. HttpResponse response = this.http.execute(httppost); httpentity entity = response.getEntity(); PrintWriter writer = new PrintWriter("filename.html","UTF-8"); if (entity != null) { InputStream instream = entity.getContent(); String line; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(instream)); while ((line = br.readLine()) != null) { writer.println(line); } } finally { instream.close(); } } writer.close(); } }
Editor: I work in Python!
jar = cookielib.FileCookieJar("cookies") opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) opener.addheaders = [('User-agent','Mozilla/5.0')] def login(): logindata = urllib.urlencode({'do' : 'login','url':'','vb_login_md5password' : password,'vb_login_md5password_utf' : password,'s' : '','vb_login_username': username,'vb_login_password': '' }) response = opener.open("http://www.sythe.org/login.PHP?do=login",logindata) def bumpThread(): if(username == "Not set" or password == "Not set"): print "Please setup password!" return if(threadNum == 0 or message == "Not set" or bumpTime == 0): print threadNum print message print "Please setup thread!" return logindata = urllib.urlencode({'title' : 'The Thread','message' : message,'wysiwyg' : '0','iconid' : '0','do' : 'postreply','t' : threadNum,'p' : '','posthash' : '','poststarttime' : '','loggedinuser' : '','multiquoteempty' : '','sbutton' : 'Submit Reply','signature' : '1','parseurl' : '1','emailupdate' : '9999' }) thread = opener.open("http://www.sythe.org/newreply.PHP?do=postreply&t=" + str(threadNum),logindata)
Solution
One thing you can try is to use the "closable httpclient" In addition, try to use basic cookiestore to realize cooking Create an httpclient object, perform any requests you need, and then close httpclient
There are other resources that may help:
>Apache httpclient documentation for state management: https://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html >Apache httpclient sample for login
The following is some sample code I wrote. It will use post to request login, and then send a get request to verify the login
The following is the implementation of my login function:
>Set proxy using credentialsprovider > set cookie using basiccookeiestore > build custom httpclient using closeablehttpclient > set post request: target, host, parameter, Path > execute post request to / login HTML login. > Execute a get request on / user to see if we log in correctly > print the status code of the response
//////// SETUP //Setup Proxy (If needed) CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope("proxy.mycompany",8080),new UsernamePasswordCredentials("my_username","my_password")); //Setup Cookies BasicCookieStore cookieStore = new BasicCookieStore(); //Build HttpClient CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .setDefaultCookieStore(cookieStore) .build(); HttpHost target = new HttpHost("www.mycompany.com",80,"http"); HttpHost proxy = new HttpHost("proxy.mycompany",8080); RequestConfig config = RequestConfig.custom() .setProxy(proxy) .build(); try { //////// LOGIN REQUEST,POST TO /login.html //Start POST Request HttpPost httppost = new HttpPost('/login.html'); //Add parameters to POST Request List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair('username','my_username')); nameValuePairs.add(new BasicNameValuePair('password','my_password')); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); //Set Config for POST Request httppost.setConfig(config); //Execute POST Request httpresponse = httpclient.execute(target,httppost); //Print Response Code try { System.out.println("Status Code: "+httpresponse.getStatusLine().getStatusCode()); } finally { //Close HTTP Reponse (must be in a 'finally' block) httpresponse.close(); } //////// CHECK LOGIN STATUS,GET TO /user //Start GET Request HttpGet httpget = new HttpGet('/user'); //Set Config for GET Request httpget.setConfig(config); //Execute GET Request httpresponse = httpclient.execute(target,httpget); //Print Response Code try { System.out.println("Status Code: "+httpresponse.getStatusLine().getStatusCode()); } finally { //Close HTTP Reponse (must be in a 'finally' block) httpresponse.close(); } } finally { httpclient.close(); }