java Android:如何使用 HttpsURLConnection 以编程方式登录网页

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7175238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:57:10  来源:igfitidea点击:

Android: How to login into webpage programmatically, using HttpsURLConnection

javaandroidhttpurlconnection

提问by Lama

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 some data from it, and after that logs out form the webpage. (and do that all programmatically)

我是 Android 新手(也是 Java 新手),如果我的问题是一个基本命题,那么抱歉!我必须编写一个 Android 应用程序,在后台登录一个 aspx 网页,从中获取一些数据,然后从网页中注销。(并以编程方式执行所有操作)

Basicly, the procedure likes getting email-list from Gmail:
1.go to 'https://mail.google.com', and signs in
2.click to the "Contacts" (== go to "https://mail.google.com/mail/?shva=1&zx=dzi4xmuko5nz#contacts")
3.fetch the page using HttpsURLConnection (or something like this), and get emails in an (e.g. Map or String) object
4.click to the "Sign out" link

基本上,该过程类似于从 Gmail 获取电子邮件列表:
1.转到“https://mail.google.com”,然后登录
2.单击“联系人”(== 转到“https://mail .google.com/mail/?shva=1&zx=dzi4xmuko5nz#contacts")
3.使用 HttpsURLConnection(或类似的东西)获取页面,并在(例如 Map 或 String)对象中获取电子邮件
4.单击“签名”出”链接

I hope, it's understandable. Looking the internet, I find the solution for only the "fetching part", so that's not a problem. But I don't have any idea about the "clicking part".

我希望,这是可以理解的。查看互联网,我只找到了“获取部分”的解决方案,所以这不是问题。但我对“点击部分”一无所知。

  ......
    // Get the connection
    URL myurl = new URL("https://mail.google.com");
    HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();

    // complete the fields
    con.setRequestProperty("Email","myacc");
    con.setRequestProperty("Passwd","mypass");

    /* 
     * in this part, should make sign in, and go directly to contacts... 
     * I don't have any idea how to do it...
     */

    // for the present, just write out the data
    InputStream ins = con.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(ins));

    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        Log.d("Page:"," "+inputLine);
    }

    in.close();

    /*
     * And here should be the "Sign out" part
     */
  ......

Any help would be great, Thank You for it! (and sorry, if my english isn't so well...)

任何帮助都会很棒,谢谢!(对不起,如果我的英语不太好......)

EDIT: problem solved. Thank You!

编辑:问题解决了。谢谢!

 .......    
    String GMAIL_CONTACTS = "https://mail.google.com/mail/?shva=1#contacts";
    String GMAIL_LOGIN = "https://mail.google.com";

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(GMAIL_LOGIN);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("Email", MY_ACC));
        nameValuePairs.add(new BasicNameValuePair("Passwd", MY_PASS));
        nameValuePairs.add(new BasicNameValuePair("signIn", "Sign In"));

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request 
        HttpResponse response = httpClient.execute(httpPost);
        Log.d(TAG, "response stat code " + response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() < 400) {

            String cookie = response.getFirstHeader("Set-Cookie")
                    .getValue();
            Log.d(TAG, "cookie: " + cookie);

            // get the contacts page 
            HttpGet getContacts = new HttpGet(GMAIL_CONTACTS);
            getContacts.setHeader("Cookie", cookie);
            response = httpClient.execute(getContacts);

            InputStream ins = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    ins));

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                Log.d(TAG, " " + inputLine);
            }

            in.close();
        } else {
            Log.d(TAG, "Response error: "
                    + response.getStatusLine().getStatusCode());
        }
 .......

回答by njzk2

"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)

1/找出该请求调用的url(如果它是网页,例如参见firebug)

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

2/找出参数是什么,找出方法是GET还是POST

3/ reproduce programmatically.

3/ 以编程方式复制。

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

4/“登录”阶段可能意味着使用 cookie,服务器为您提供该 cookie,之后您必须为每个请求发回

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.

但是,您的方法是错误的。您不应该尝试通过 url 连接直接登录到 google。(你也应该使用 HttpClient)。此外,请求属性不是参数。他们是标题。

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

我强烈建议您从更简单的东西开始,以便熟悉 Java、GET、POST、参数、标头、响应、cookie 中的 HTTP……

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 :

它会告诉您登录成功。(2xx 成功,3xx 移动等等。4xx 是请求中的错误,5xx 是服务器端错误;Gmail 响应 302 登录以建议重定向到收件箱)。然后,您会注意到响应“Set-Cookie”中有一个特定的标头,其中包含您想要用于进一步连接的 cookie,因此:

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.

它应该是这样的。

回答by Peter Knego

What you are trying to do is parse the Gmail html page. This is wrongn approach as Gmail uses javascript to build the page. Your code would have to emulate browser (execute javascript) for this to work.

您要做的是解析 Gmail html 页面。这是错误的方法,因为 Gmail 使用 javascript 来构建页面。您的代码必须模拟浏览器(执行 javascript)才能使其工作。

If you only need read access to Gmail then use Gmail inbox feed API. This gives you access to unread messages in inbox.

如果您只需要 Gmail 的读取权限,请使用Gmail 收件箱提要 API。这使您可以访问收件箱中的未读邮件。

If you need full access then see the Gmail IMAP access. As IMAP is a different protocol then HTTP you'd need to use separate IMAP library for java. See this tutorial.

如果您需要完全访问权限,请参阅Gmail IMAP 访问权限。由于 IMAP 是与 HTTP 不同的协议,因此您需要为 java 使用单独的 IMAP 库。请参阅本教程

回答by Snicolas

You should consider using a post request to pass data to the server : Sending POST data in Android

您应该考虑使用 post 请求将数据传递到服务器:在 Android 中发送 POST 数据

Chaging the properties of a connection has nothing to do with what you want to achieve.

更改连接的属性与您要实现的目标无关。

Regards, Stéphane

问候, 斯蒂芬