Android: How to login into webpage programmatically, using HttpsURLConnection

前端 未结 3 1605
不知归路
不知归路 2021-02-06 14:48

I\'m new in Android (and in Java too), so sorry if my problem is a basic proposition! I have to write an Android app, whitch signs into an aspx webpage in the background, get s

3条回答
  •  感情败类
    2021-02-06 15:46

    "Clicking" is basically sending a request to a server and displaying the return informations.

    1/ find out what url to call for that request (if it is a web page, see firebug for example)

    2/ find out what the parameters are, find out if the method is GET or POST

    3/ reproduce programmatically.

    4/ a "login" phase probably imply the use of a cookie, which the server gives you and that you must send back afterward for each request

    However, your approach is wrong. You should not try to login directly to google via url connections. (Also you should use HttpClient). Moreover, request properties are not parameters. They are headers.

    I strongly recommend you start with something simpler in order to get comfortable with HTTP in java, GETs, POSTs, parameters, headers, responses, cookies ...

    edit

    Once you receive the response, you'll want to check that

    response.getStatusLine().getStatusCode() < 400
    

    It will tell you that login was successful. (2xx are success, 3xx are moved and such. 4xx are errors in the request, 5xx are server side errors ; Gmail responds 302 to login to suggest redirection to inbox). Then, you'll notice that there is a particular header in the response "Set-Cookie" that contains the cookie you want for further connections so :

    String cookie = response.getFistHeader("Set-Cookie");
    

    Then, you should be able to call the request to get the contacts :

    HttpGet getContacts = new HttpGet(GMAIL_CONTACTS);
    getContacts.setHeader("Cookie", cookie);
    response = httpClient.execute(getContacts);
    InputStream ins = response.getEntity().getContent();
    

    It should be something like that.

提交回复
热议问题