登录无效

时间:2012-01-29 17:03:18

标签: java android login http-post http-get

我正在尝试创建一个登录应用程序,以便您可以查看成绩/电子邮件教师/等。 我可以做到这一切,但我无法登录为我的生活工作。 我每次尝试都会得到:

  

无法从会话中检索user_id。用户超时。   块引用

我不知道我的代码有什么问题以及为什么我无法登录。 有人请帮帮我。谢谢。

主要“登录”代码:

public class GradePortalActivity extends Activity {
    private final static String SITE = "http://dcps.mygradeportal.com/";
    private TextView usernameField, passwordField;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MySoup.setSite(SITE);
        usernameField = (TextView) this.findViewById(R.id.usernameField);
        passwordField = (TextView) this.findViewById(R.id.passwordField);
    }

    public void login(View v) {
        if (usernameField.length() > 0 && passwordField.length() > 0)
            new Login().execute(new String[] { usernameField.getText().toString().trim(), passwordField.getText().toString() });
        else {
            Toast.makeText(this, "Fill out login form", Toast.LENGTH_LONG).show();
        }
    }

    private class Login extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            lockScreenRotation();
            dialog = new ProgressDialog(GradePortalActivity.this);
            dialog.setIndeterminate(true);
            dialog.setMessage("Logging in...");
            dialog.show();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            String username = params[0];
            String password = params[1];
            try {
                MySoup.login(username, password);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean status) {
            dialog.dismiss();
            if (status == true) {
                Toast.makeText(GradePortalActivity.this, "Logged in", Toast.LENGTH_LONG).show();
                new Test().execute();
            }
            if (status == false) {
                Toast.makeText(GradePortalActivity.this, "Log in failed", Toast.LENGTH_LONG).show();
            }
        }
    }

    private class Test extends AsyncTask<String, Void, String> {
        private ProgressDialog dialog;

        @Override
        protected String doInBackground(String... params) {
            String s = MySoup.inputStreamToString(MySoup.scrape("http://dcps.mygradeportal.com/homepage.aspx"));
            return s;
        }

        @Override
        protected void onPostExecute(String s) {
            Toast.makeText(GradePortalActivity.this, s, Toast.LENGTH_LONG).show();
        }
    }

    private void lockScreenRotation() {
        switch (this.getResources().getConfiguration().orientation) {
        case Configuration.ORIENTATION_PORTRAIT:
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            break;
        case Configuration.ORIENTATION_LANDSCAPE:
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            break;
        }
    }

    private void unlockScreenRotation() {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    }   
}

“MYSOUP”代码(申请的主干):

public class MySoup {

    /** The http client. */
    private static DefaultHttpClient httpClient = getHttpClient();

    /** The cookies. */
    private static List<Cookie> cookies;

    /** The http params. */
    private static HttpParams httpParams = httpClient.getParams();

    /** The username. */
    private static String username;

    /** The SITE. */
    private static String SITE;

    /** The httpget. */
    private static HttpGet httpget;

    /** The response. */
    private static HttpResponse response;

    /** The entity. */
    private static HttpEntity entity;

    /** The httpost. */
    private static HttpPost httpost;

    public static void setSite(String s) {
        if (!s.endsWith("/")) {
            s = s + "/";
        }
        if (!s.startsWith("http://") || s.startsWith("https://")) {
            s = "http://" + s;
        }
        SITE = s;
    }

    /**
     * Gets the site.
     * 
     * @return the site
     */
    public static String getSite() {
        return SITE;

    }

    /**
     * Gets the http client.
     * 
     * @return the http client
     */
    private static DefaultHttpClient getHttpClient() {
        DefaultHttpClient client = new DefaultHttpClient();
        ClientConnectionManager mgr = client.getConnectionManager();
        HttpParams params = client.getParams();



        client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);
        return client;
    }

    /**
     * Gets the session id.
     * 
     * @return the session id
     */
    public static String getSessionId() {
        return cookies.get(0).getValue();
    }

    /**
     * Gets the cookies.
     * 
     * @return the cookies
     */
    public static List<Cookie> getCookies() {
        return cookies;
    }

    /**
     * Checks if is logged in.
     * 
     * @return true, if is logged in
     */
    public static boolean isLoggedIn() {
        if ((cookies != null) && !cookies.isEmpty())
            return true;
        else
            return false;
    }

    /**
     * Login.
     * 
     * @param url
     *            the url
     * @param username
     *            the username
     * @param password
     *            the password
     * @throws CouldNotLoadException
     *             the could not load exception
     */
    public static void login(String username, String password) throws Exception {
        String url = SITE;

        try {
            httpget = new HttpGet(url);
            response = httpClient.execute(httpget);
            entity = response.getEntity();

            httpost = new HttpPost(url);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("userName", username));
            nvps.add(new BasicNameValuePair("password", password));

            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            response = httpClient.execute(httpost);
            entity = response.getEntity();
            if (entity != null) {
            entity.consumeContent();
            cookies = httpClient.getCookieStore().getCookies();
            }} catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Could not login");
            }

            }



    /**
     * Scrape.
     * 
     * @param url
     *            the url
     * @return the input stream
     */
    public static InputStream scrape(String url) {
        httpget = new HttpGet(url);
        response = null;
        try {
            response = httpClient.execute(httpget);
            entity = response.getEntity();
            InputStream s = entity.getContent();
            System.err.println("encoding " + entity.getContentEncoding());
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * Input stream to string.
     * 
     * @param is
     *            the is
     * @return the string
     */
    public static String inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();

        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return total.toString();
    }

    /**
     * Press link.
     * 
     * @param url
     *            the url
     */
    public static void pressLink(String url) {
        url = SITE + url;
        httpget = new HttpGet(url);
        response = null;
        try {
            response = httpClient.execute(httpget);
            response.getEntity().consumeContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Gets the username.
     * 
     * @return the username
     */
    public static String getUsername() {
        return username;
    }

    /**
     * Sets the session id.
     * 
     * @param sessionId
     *            the new session id
     */
    public static void setSessionId(String sessionId) {
        Cookie cookie = new BasicClientCookie("", sessionId);
        CookieStore cs = new BasicCookieStore();
        cs.addCookie(cookie);
        httpClient.setCookieStore(cs);
        cookies = httpClient.getCookieStore().getCookies();
    }

}

1 个答案:

答案 0 :(得分:1)

“错误”:

Could not retrieve user_id from the session. User timed out.

是从这一行生成的:

String s = MySoup.inputStreamToString(MySoup.scrape("http://dcps.mygradeportal.com/homepage.aspx"));

如果您浏览到http://dcps.mygradeportal.com/homepage.aspx,您会看到您的服务器产生以下错误:

  应用程序中的服务器错误。

     

无法从会话中检索user_id。用户超时

     

描述:执行期间发生了未处理的异常   当前的网络请求。请查看堆栈跟踪了解更多信息   有关错误的信息以及它在代码中的起源。

     

异常详细信息:OnCourse.Core.SWSException:无法检索   来自会话的user_id。用户超时

     

等...

所以我怀疑正在发生的事情是你应该在抓取 http://dcps.mygradeportal.com/homepage.aspx时传递一些POST参数,你不是这样做的。其中一个参数可能是难以捉摸的user_id

请注意,我无法确切地告诉您这一点,因为我不知道gradeportal服务的工作原理,但这可以帮助您解决问题。