Toon posts:

[JAVA] gebruik HttpClient lukt niet op google

Pagina: 1
Acties:

Verwijderd

Topicstarter
Beste medegotters,

Ik moet een applicatie maken die geautomatiseerd rapporten ophaalt van google analytics. Daar is nu geen api voor dus dacht ik dat het handig zou zijn om dit niet handmatig te doen maar dmv het gebruik van HttpClient.

Nu ben ik een beetje aan het prutsen en loop ik een beetje vast. Ik heb het voorbeeld gebruikt van httpclient en ingesteld zoals het volgens mij moet maar ik krijg continu een 302 en de cookies onthoud hij niet. Als hij eenmaal de login heeft gedaan en de cookie pakt dan kan ik alle rapporten gewoon opvragen.

Weet iemand waarom ik niet in kan loggen, geen cookie laat zien en wat ik verkeerd doe?

Code:
Java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
 import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.*;

/**
 * <p>
 * A example that demonstrates how HttpClient APIs can be used to perform 
 * form-based logon.
 * </p>
 *
 * @author Oleg Kalnichevski
 *
 */
public class FormLoginDemo
{
    static final String LOGON_SITE = "www.google.com";
    static final int    LOGON_PORT = 443;

    public FormLoginDemo() {
        super();
    }

    public static void main(String[] args) throws Exception {

        HttpClient client = new HttpClient();
        client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "https");
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);


        GetMethod authget = new GetMethod("/accounts");

        client.executeMethod(authget);
        System.out.println("Login form get: " + authget.getStatusLine().toString()); 
        // release any connection resources used by the method
        authget.releaseConnection();
        // See if we got any cookies
        CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
        Cookie[] initcookies = cookiespec.match(
            LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());
        System.out.println("Initial set of cookies:");    
        if (initcookies.length == 0) {
            System.out.println("None");    
        } else {
            for (int i = 0; i < initcookies.length; i++) {
                System.out.println("- " + initcookies[i].toString());    
            }
        }
        
        PostMethod authpost = new PostMethod("/accounts");
        // Prepare login parameters
        NameValuePair action   = new NameValuePair("action", "ServiceLoginBoxAuth");
        NameValuePair url      = new NameValuePair("url", "/ServiceLoginBox?continue=http%3A%2F%2Fwww.google.com%2Fanalytics%2Fhome%2F%3Fet%3Dreset%26hl%3Dnl-NL&service=analytics&nui=1&hl=nl-NL");
        NameValuePair Email = new NameValuePair("Email ", "*****");
        NameValuePair Passwd = new NameValuePair("Passwd", "***");
        authpost.setRequestBody( 
          new NameValuePair[] {action, url, Email, Passwd });
        
        client.executeMethod(authpost);
        System.out.println("Login form post: " + authpost.getStatusLine().toString()); 
        // release any connection resources used by the method
        authpost.releaseConnection();
        // See if we got any cookies
        // The only way of telling whether logon succeeded is 
        // by finding a session cookie
        Cookie[] logoncookies = cookiespec.match(
            LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());
        System.out.println("Logon cookies:");    
        if (logoncookies.length == 0) {
            System.out.println("None");    
        } else {
            for (int i = 0; i < logoncookies.length; i++) {
                System.out.println("- " + logoncookies[i].toString());    
            }
        }
        // Usually a successful form-based login results in a redicrect to 
        // another url
        int statuscode = authpost.getStatusCode();
        if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||
            (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||
            (statuscode == HttpStatus.SC_SEE_OTHER) ||
            (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
            Header header = authpost.getResponseHeader("location");
            if (header != null) {
                String newuri = header.getValue();
                if ((newuri == null) || (newuri.equals(""))) {
                    newuri = "/";
                }
                System.out.println("Redirect target: " + newuri); 
                GetMethod redirect = new GetMethod(newuri);

                client.executeMethod(redirect);
                System.out.println("Redirect: " + redirect.getStatusLine().toString()); 
                // release any connection resources used by the method
                redirect.releaseConnection();
            } else {
                System.out.println("Invalid redirect");
                System.exit(1);
            }
        }
    }
} 

  • ari3
  • Registratie: Augustus 2002
  • Niet online
Je hebt te maken met een redirect:
302 Found

The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.

The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Note: RFC 1945 and RFC 2068 specify that the client is not allowed
to change the method on the redirected request. However, most
existing user agent implementations treat 302 as if it were a 303
response, performing a GET on the Location field-value regardless
of the original request method. The status codes 303 and 307 have
been added for servers that wish to make unambiguously clear which
kind of reaction is expected of the client.
bron

"Kill one man, and you are a murderer. Kill millions of men, and you are a conqueror. Kill them all, and you are a god." -- Jean Rostand


  • Kuhlie
  • Registratie: December 2002
  • Niet online
Uit ervaring weet ik dat Google JavaClients weert. Je moet een HttpUrlConnection gebruiken en dan met iets van setHeader of addHeader ofzo aangeven dat je bijv. internet explorer bent.

Edit: bijna goed, het gaat om: http://java.sun.com/j2se/...ring,%20java.lang.String)

Edit2: oh, je gebruikt andere api's. Nouja, het verhaal blijft hetzelfde: doe net alsof je een 'normale' browser bent dmv de juiste header ("User-Agent"?).

[ Voor 51% gewijzigd door Kuhlie op 05-01-2007 13:40 ]


Verwijderd

Topicstarter
Bedankt voor alle reply's , de fout zat in de url deze moest zijn om in te loggen: https://www.google.com/accounts/LoginAuth

Dan ontving ik een cookie en kon ik alle andere pagina's hard opvragen.