0

I try to send POST data to a Website. But the "login" will not work. Slowly i dont know why. There are quite a lot of ways to login to a website without browser-ui. What is the "best" method to login here ? I uses Jsoup and "normal" HttpURLConnection. With Selenium it works fine, but very slow =(

import com.gargoylesoftware.htmlunit.util.Cookie;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.*;
import java.util.List;
import java.util.Map;

public class postget {

        private static final String USER_AGENT = "Mozilla/5.0";

        private static final String GET_URL = "https://de.metin2.gameforge.com/";

        private static final String POST_URL = "https://de.metin2.gameforge.com:443/user/login?__token=";//+token

        private static final String POST_PARAMS = "username=USERNAME"+"password=PASSWORD";

        static final String COOKIES_HEADER = "Set-Cookie";
        public static void main(String[] args) throws IOException {

            String var = sendGET();
            String var1 =var.substring(0,var.indexOf(";"));
            String var2 =var.substring(var.indexOf(";")+1,var.indexOf(":"));
            String token =var.substring(var.indexOf(":")+1);
            //sendPOST(token,cookie);
            jsoup(cookie(),token);
        }
        private static String sendGET() throws IOException {
            URL obj = new URL(GET_URL);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("User-Agent", USER_AGENT);
            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                String veri1=response.substring(response.indexOf("verify-v1")+20,response.indexOf("verify-v1")+63);
                String veri2=response.substring(response.indexOf("verify-v1")+104,response.indexOf("verify-v1")+147);
                String token=response.substring(response.indexOf("token")+6,response.indexOf("token")+38);
                return (veri1+";"+veri2+":"+token);
            } else {
                System.out.println("GET request not worked");
                return " ";
            }
        }
        private static String cookie() throws IOException{
            String realCookie="";
            URL obj = new URL(GET_URL);
            HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
             java.net.CookieManager msCookieManager = new java.net.CookieManager();

            Map<String, List<String>> headerFields = connection.getHeaderFields();
            List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);

            if (cookiesHeader != null) {
                for (String cookie : cookiesHeader) {
                    msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));
                }
            }
            List<HttpCookie> cookiess = msCookieManager.getCookieStore().getCookies();

            if (cookiess != null) {
                if (cookiess.size() > 0) {
                    for (HttpCookie cookie : cookiess) {
                        realCookie = cookie.toString().substring(cookie.toString().indexOf("=")+1);
                        return(realCookie);
                    }
                }
            }
            return(realCookie);
        }
        private static void sendPOST(String token,CookieManager msCookieManager) throws IOException {
            URL obj = new URL(POST_URL+token);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", USER_AGENT);

            if (msCookieManager != null) {

                List<HttpCookie> cookies = msCookieManager.getCookieStore().getCookies();

                if (cookies != null) {
                    if (cookies.size() > 0) {
                        for (HttpCookie cookie : cookies) {
                            String realCookie = cookie.toString().substring(cookie.toString().indexOf("=")+1);
                        }
                        con.setRequestProperty("Cookie", StringUtils.join(cookies, ";"));
                    }
                }
            }

            // For POST only - START
            con.setDoOutput(true);
            OutputStream os = con.getOutputStream();
            os.write(POST_PARAMS.getBytes());
            os.flush();
            os.close();
            // For POST only - END

            int responseCode = con.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) { //success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // print result
                if(response.indexOf("form-login")>0){
                    System.out.println("NOPE");
                }
                if(response.indexOf("logout")>0){
                    System.out.println("YES");
                }

            } else {
                System.out.println("POST request not worked");
            }
        }
        private static void jsoup(String cookie,String token) throws IOException{
           Document response = Jsoup.connect("https://de.metin2.gameforge.com/")

                    .referrer("https://de.metin2.gameforge.com/main/index?__token=5"+token)
                    .cookie("Cookie","gf-locale=de_DE; _ga=GA1.2.404625572.1501231885; __auc=a02de56115d8864ad2bd7ad8120; pc_idt=ANu-cNegKMzU8CAsBQAHIu1cRlXEEUD1ka6NvJXWqO4sVVaLIsqSFPyZFt8dXHKcrhrB_u2FFdQnD-2vsA377NnVgjkrKn-3qzi5Q3LXbzgnbbmIEir4zYNCddPbjCUg9cVpSU4GP-CvU53XhrQ6_MWP9tOYNdjCqRVIPw; SID="+cookie+"; __utma=96667401.404625572.1501231885.1503225538.1503232069.15; __utmc=96667401; __utmz=96667401.1501247623.3.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)")
                    //.data("X-DevTools-Emulate-Network-Conditions-Client-Id","c9bbb769-df80-47ff-8e25-e582de026ecc")
                    .userAgent("Mozilla")
                    .data("username", "USERNAME")
                    .data("password", "PASSWORD")
                    .post();

               System.out.println(response);

           }
        }
    }

The var1 and var1 are unnecessary. They was my first idea to send with my POST.

Here is a picture if the login-form: And of HttpClient LOGIN-Form

enter image description here

V0lvox337
  • 132
  • 1
  • 10
  • Post parameters do not work that way. As there are some small imperfections, like not specifying a charset for InputStreamReader, maybe just use apache HttpClient - a similar API will be incorporated in java 9. Use development tools in the browser to check how a post is given (the raw data). – Joop Eggen Aug 20 '17 at 13:30
  • Thank you. I will write this "request" with HttpClient and will see how it works. At the moment i use the Network-Manager(F12) and HTTP-Headers(chrome). – V0lvox337 Aug 20 '17 at 13:38
  • what are the parameter i should send in the POST ? the token ? the Cookie ? just the User data ? – V0lvox337 Aug 20 '17 at 15:38
  • https://stackoverflow.com/questions/14551194/how-are-parameters-sent-in-an-http-post-request – Joop Eggen Aug 20 '17 at 20:58

0 Answers0