Android的:如何以编程方式登录到网站,并从中检索数据? [英] Android: How to programatically login to website and retrieve data from it?

查看:210
本文介绍了Android的:如何以编程方式登录到网站,并从中检索数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,伙计们,所以我最近开发Android应用程序,节省了用户的ID和密码共享preferences。现在,当用户启动应用程序第二次,他将直接重定向到MainActivity在ListView的几个选项。现在我有一个巨大的头痛和它的驾驶我疯狂REAL。我无法登录到网站和数据获取到我的手机。我一直在使用HTTP(S)的URLConnection,HttpClient的尝试,但它只是似乎并没有为我工作。所有我从POST方法得到的是登录页面的源$ C ​​$ C。

Ok, guys, so I'm recently developing android app that saves user's ID and PASSWORD to SharedPreferences. Now, when the user starts app second time, he will be redirected directly to MainActivity with a few options in listView. And now I have a huge headache and it's driving me REAL crazy. I cannot login to website and fetch the data to my phone. I've tried using Http(s)UrlConnection, HttpClient, but it just doesn't seem to work for me. All I get from POST method is a source code of login page.

现在,有登录页面: https://medeine.vgtu.lt /studentams/login.jsp?klb=en

和我的目标页: https://medeine.vgtu.lt/studentams/pask_stud.jsp < - 我需要获取从那里数据

and my target page: https://medeine.vgtu.lt/studentams/pask_stud.jsp <-- I need to fetch data from there

你有什么想法或提示/方法/指南/什么怎么办?

Have you got any thoughts or tips/methods/guides/anything how to do that?

推荐答案

有关这一点,你必须派两个POST请求。在第一REQ需要发送的登录数据并保存成功,如果登录的Cookie。在第二个请求发送需要保存的cookies,你可以得到的数据。
对于POST数据的格式必须像这样:var =值&安培; VAR2 = VALUE2
你的情况:

For this you must sent two POST requests. In first req need send login data and save cookies if success login. In second request need send saved cookies and you can get the data. Data for POST must be formatted like this: var=value&var2=value2 In your case:

String data = "studKnNr=login&asmKodas=password";

和URL的请求: https://medeine.vgtu.lt/studentams/submit.jsp

看下面code:

String data = "studKnNr=login&asmKodas=password";
String loginUrl = "https://medeine.vgtu.lt/studentams/submit.jsp";
String Login = POST_req(loginUrl, data, 10000); /*last parameter is a limit of page content length*/

//And adter succcess login you can send second request:
String pageContent = POST_req(someUrl, "", 10000);


//Methods for sending requests and saving cookie: 
//(this no needs for changing, can only past to you project)
public String POST_req(String url, String post_data, int len) {
    URL addr = null;
    try {
            addr = new URL(url);
        } catch (MalformedURLException e) {
            return "Некорректный URL";
        }
        StringBuffer data = new StringBuffer();
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) addr.openConnection();
        } catch (IOException e) {
            return "Open connection error";
        }
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Accept-Language", "ru,en-GB;q=0.8,en;q=0.6");
        conn.setRequestProperty("Accept-Charset", "utf-8");
        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        conn.setRequestProperty("Cookie", "");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        //conn.setInstanceFollowRedirects(true);
        set_cookie(conn);

        //POST data: 
        String post_str = post_data;
        data.append(post_str);
        try {
            conn.connect();
        } catch (IOException e) {
            return "Connecting error";
        }
        DataOutputStream dataOS = null;
        try {
            dataOS = new DataOutputStream(conn.getOutputStream());
        } catch (IOException e2) {
            return "Out stream error";
        }
        try {
            ((DataOutputStream) dataOS).writeBytes(data.toString());
        } catch (IOException e) {
            return "Out stream error 1";
        }

        /*If redirect: */
        int status;
        try {
            status = conn.getResponseCode();
        } catch (IOException e2) {
            return "Response error";
        }
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) {
            String new_url = conn.getHeaderField("Location");
            String cookies = conn.getHeaderField("Set-Cookie");
            URL red_url;
            try {
                red_url = new URL(new_url);
            } catch (MalformedURLException e) {
                return "Redirect error";
            }
            try {
                conn = (HttpURLConnection) red_url.openConnection();
            } catch (IOException e) {
                return "Redirect connection error";
            }
            //conn.setRequestProperty("Content-type", "text/html");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Accept-Language", "ru,en-GB;q=0.8,en;q=0.6");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            conn.setRequestProperty("Cookie", cookies);     
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //conn.setInstanceFollowRedirects(true);
        }

        java.io.InputStream in = null;
        try {
            in = (java.io.InputStream) conn.getInputStream();
        } catch (IOException e) {
            return "In stream error";
        }
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(in, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return "In stream error";
        }
        char[] buf = new char[len];
        try {
            reader.read(buf);
        } catch (IOException e) {
            return "In stream error";
        }
        get_cookie(conn);

        return (new String(buf));
    }
    public void get_cookie(HttpURLConnection conn) {
        SharedPreferences sh_pref_cookie = getSharedPreferences("cookies", Context.MODE_PRIVATE);
        String cook_new;
        String COOKIES_HEADER;
        if (conn.getHeaderField("Set-Cookie") != null) {
            COOKIES_HEADER = "Set-Cookie";
        }
        else {
            COOKIES_HEADER = "Cookie";
        }
        cook_new = conn.getHeaderField(COOKIES_HEADER);
        if (cook_new.indexOf("sid", 0) >= 0) {
            SharedPreferences.Editor editor = sh_pref_cookie.edit();
            editor.putString("Cookie", cook_new);
            editor.commit();
        }
    }
    public void set_cookie(HttpURLConnection conn) {
        SharedPreferences sh_pref_cookie = getSharedPreferences("cookies", Context.MODE_PRIVATE);
        String COOKIES_HEADER = "Cookie";
        String cook = sh_pref_cookie.getString(COOKIES_HEADER, "no_cookie");
        if (!cook.equals("no_cookie")) {
            conn.setRequestProperty(COOKIES_HEADER, cook);
        }
    }

当然,你必须在非同步线程发送请求。

Of course you must send requests in asynch thread.

希望它帮助。和原谅我的英语不好:)

Hope it helpful. And excuse me for my bad english:)

这篇关于Android的:如何以编程方式登录到网站,并从中检索数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆