Я пытаюсь создать приложение для входа, чтобы вы могли просматривать оценки / учителей по электронной почте / и т.д.и я могу сделать все это, но я не могу получить логин, чтобы работать на всю жизнь.Каждый раз, когда я пытаюсь получить, я получаю:
Не удалось получить 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();
}
}