0

私は初心者で、うまくいく解決策を見つけることができません。

やりたいこと: ユーザーがユーザー名とパスワードを入力すると、アプリケーションが Web サイトにログインします。ログインに失敗した場合は false と適切なメッセージを返します。それ以外の場合は true を返し、次のアクティビティに進みます (別のサイトを取得し、html を解析し、コンテンツを表示します)。

私が立ち往生している場所:ログインの成功を検出するにはどうすればよいですか?

これが私のコードです

LoginActivityからの関連コード:

    Authentication auth = new Authentication();                     
    boolean loginSuccess = auth.authenticateUser(username, pass);

    if (!loginSuccess) {
        Toast.makeText(getBaseContext(), 
                "Invalid username or password.", 
                Toast.LENGTH_SHORT).show();                                                 
    }

    else {
        Intent intent = new Intent(LoginActivity.this, MenuActivity.class);
        LoginActivity.this.startActivity(intent);
    }   

Authenticationクラスのメソッド:

public boolean authenticateUser(String username, String pass) {

boolean loginSuccess = false;       
HttpRequest httpRequest = new HttpRequest();        
String result = "";

try {           
    result = httpRequest.getResult(username, pass);
    Log.d("RESULT", result);            

        // Checking if it was a successful login    
    if (**SOMETHING**) loginSuccess = true;         
    } catch (ParseException e) {            
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }           

return loginSuccess;                
}

200 (OK) ステータスを取得したので、POST のコードは問題なく動作すると思います。そのため、ここではHttpRequestクラス全体を配置せず、最も重要なメソッドのみを配置します。

public String getResult(String username, String pass) throws ParseException, IOException {
    String result = "";
    response = postData(username, pass);
    entity = response.getEntity();
    if (entity != null) {
        result = EntityUtils.toString(response.getEntity());                    
    }   

    return result;
}       

public HttpResponse postData(String username, String password) throws ClientProtocolException, IOException {
    HttpPost httpPost = getHttpPost(username, password);            
    HttpClient httpClient = getHttpClient();
    return httpClient.execute(httpPost);                
}

private HttpPost getHttpPost(String username, String password) throws UnsupportedEncodingException {
    String url = "https://www.sitename.com/login.aspx";
    HttpPost httpPost = new HttpPost(url);      

    List<NameValuePair> parameters = new ArrayList<NameValuePair>(2);
    parameters.add(new BasicNameValuePair("txtUsername", username));
    parameters.add(new BasicNameValuePair("txtPassword", password));                
    httpPost.setEntity(new UrlEncodedFormEntity(parameters));

    return httpPost;        
}

したがって、欠けているのは Authentication クラスのコードの一部であり、ログインが成功したかどうかを確認する必要があります。取得した結果変数 (またはresponse、またはentity )をどうするかわかりません。

4

1 に答える 1

0

ログインが成功したと言うには、200 (OK) ステータスで十分だと思います。それ以外の場合は、401 拒否ステータス コードが返されます。この質問RESTful ログインの失敗: 401 またはカスタム応答を返すを参照してください。getResultを変更して Boolean を返し、ステータスが OK の場合にtruegetResultを返すように変更することができます。

于 2012-09-10T22:54:48.753 に答える