httpclient w jave

0

Witam, mam problem z którym walcze od dłuższego czasu, mianowicie chodzi o kod przez który zaloguje się do strony. Dokładniej mówiąc mam formularz w javie (JForm + Jtextfield) i gotowy dzialający prosty skrypt w php. Chciałbym zrobić abym mógł się zalogować na stronie i pobierać dane prosto z php. Wszystko działa jak należy jeśli chodzi o rejestracje, kod wysyła $_POST i użytkownik jest zakładany. Gorzej jest z logowaniem ponieważ nie potrafie utrzymać sesji :/

Próbowałem już na tyle sposobów że nie wiem który fragment kodu dodac :)

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(POST_URL);
        httpPost.addHeader("User-Agent", USER_AGENT);
 
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("login", "[email protected]"));
        urlParameters.add(new BasicNameValuePair("password", "ja"));
 
        HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
        httpPost.setEntity(postParams);
 
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
 
        System.out.println("POST Response Status:: "
                + httpResponse.getStatusLine().getStatusCode());
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpResponse.getEntity().getContent()));
 
        String inputLine;
        StringBuffer response = new StringBuffer();
 
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();
 
        // print result
        System.out.println(response.toString());
        httpClient.close(); 

Wiem że w jakiś sposób musze przetrzymać cookie ale nie mam pojęcia jak to zrobic :)

0

Dalej nie potrafie się tym posłużyć, zasada dzialania jest taka: ja wysylam zapytanie do strony np login.php i ona narzuca mi sesje, pozniej chce poprzez $_GET pobrac z innej strony np dane.php te dane ktore ona zwroci, czyli w tym przypadku jest to tekst zalogowano / niezalogowano i print_r($_SESSION);

 

        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // Create a local instance of cookie store
            CookieStore cookieStore = new BasicCookieStore();

            // Create local HTTP context
            HttpClientContext localContext = HttpClientContext.create();
            // Bind custom cookie store to the local context
            localContext.setCookieStore(cookieStore);

            HttpGet httpget = new HttpGet("http://localhost/login/login");
            System.out.println("Executing request " + httpget.getRequestLine());

            // Pass local context as a parameter
            CloseableHttpResponse response = httpclient.execute(httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                List<Cookie> cookies = cookieStore.getCookies();
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("Local cookie: " + cookies.get(i));
                }
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        
        
        new post_test().sendGET("http://localhost/login/dane");
        
 

    private static void sendGET(String GET_URL) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(GET_URL);
        httpGet.addHeader("User-Agent", USER_AGENT);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
 
        System.out.println("GET Response Status:: "
                + httpResponse.getStatusLine().getStatusCode());
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpResponse.getEntity().getContent()));
 
        String inputLine;
        StringBuffer response = new StringBuffer();
         StringBuffer result = new StringBuffer();
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
                result.append(inputLine);
        }
        reader.close();
 
        // print result
        System.out.println(response.toString());
        httpClient.close();
    }

Może po prostu później źle odczytuje sesje / źle wysyłam zapytanie ?

to zwraca mi konsola:

run:
Executing request GET http://localhost/login/login HTTP/1.1
----------------------------------------
HTTP/1.1 200 OK
Local cookie: [version: 0][name: PHPSESSID][value: lh7urs78uu5v6lkcuruvupfbd4][domain: localhost][path: /][expiry: null]
GET Response Status:: 200
Array()notlogged
BUILD SUCCESSFUL (total time: 1 second)

Array()notlogged wyświetla się gdy nie jestem prawidłowo zalogowany :)


0

A w prze glądarce nie możesz zobaczyć jakie nagłówki latają i postąpić tak samo

0

Teraz to juz kompletnie nie wiem o co chodzi, znalazlem jeszcze jakies dodatkowe rozwiazania i nic nie dziala :/

Sprawdzilem również nagłówki za pomocą firebuga, ale nic mi to nie zmienia :/

        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // Create a local instance of cookie store
            CookieStore cookieStore = new BasicCookieStore();

            // Create local HTTP context
            HttpClientContext localContext = HttpClientContext.create();
            // Bind custom cookie store to the local context
            localContext.setCookieStore(cookieStore);

            HttpGet httpget = new HttpGet("http://localhost/login/setsession");
            System.out.println("Executing request " + httpget.getRequestLine());

            // Pass local context as a parameter
            CloseableHttpResponse response = httpclient.execute(httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                List<Cookie> cookies = cookieStore.getCookies();
                System.out.println(cookies.toArray());
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("Local cookie: " + cookies.get(i));
                }
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        
        
//        new post_test().sendGET("http://localhost/login/loggedreturn");
        

// your first request that does the authentication
URL authUrl = new URL(POST_URL);
HttpsURLConnection authCon = (HttpsURLConnection) authUrl.openConnection();
authCon.connect();

// temporary to build request cookie header
StringBuilder sb = new StringBuilder();

// find the cookies in the response header from the first request
List<String> cookies = authCon.getHeaderFields().get("Set-Cookie");
if (cookies != null) {
    for (String cookie : cookies) {
        if (sb.length() > 0) {
            sb.append("; ");
        }

        // only want the first part of the cookie header that has the value
        String value = cookie.split(";")[0];
        sb.append(value);
    }
}

// build request cookie header to send on all subsequent requests
String cookieHeader = sb.toString();

// with the cookie header your session should be preserved
URL regUrl = new URL("http://localhost/login/loggedreturn");
HttpsURLConnection regCon = (HttpsURLConnection) regUrl.openConnection();
regCon.setRequestProperty("Cookie", cookieHeader);
regCon.connect();
        regCon.getDoOutput();
        System.err.println(regCon.getDoOutput());
    }

Kod php:

plik1.php
session_start()
$_SESSION['user'] = "test";

plk2.php
session_start();
if($_SESSION['user'] != null){
echo 'dziala';
}else{
echo 'nie dziala';
}
 

Czy pod taki banalny kod, istnieje gdzieś gotowy kod javy abym mógł sobie porównać jak ma dzialac dokladnie httpclient ?

0

czy ktos moze pomoc ?

1 użytkowników online, w tym zalogowanych: 0, gości: 1