Android:如何以编程方式登录网站并从中检索数据?

emi*_*ius 2 java post android httpclient httpurlconnection

好的,大家好,所以我最近开发的android应用程序将用户的ID和PASSWORD保存到SharedPreferences.现在,当用户第二次启动应用程序时,他将通过listView中的一些选项直接重定向到MainActivity.而现在我头疼得厉害,这让我变得非常疯狂.我无法登录网站并将数据提取到手机.我尝试过使用Http(s)UrlConnection,HttpClient,但它似乎对我不起作用.我从POST方法得到的只是登录页面的源代码.

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

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

你有任何想法或提示/方法/指南/任何如何做到这一点?

Con*_*ine 5

为此,您必须发送两个POST请求.在第一次请求中,如果成功登录,则需要发送登录数据并保存cookie.在第二个请求中,需要发送已保存的cookie,您可以获取数据.POST的数据必须格式如下:var = value&var2 = value2

在你的情况下:

String data = "studKnNr=login&asmKodas=password";
Run Code Online (Sandbox Code Playgroud)

并请求网址:https://medeine.vgtu.lt/studentams/submit.jsp

看下面的代码:

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 after 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

当然,您必须在异步线程中发送请求.

希望它有用.请原谅我的英语不好:)